Indication of lifetimes in types of function pointers in the structure

I have a function foodefined as follows:

fn foo<'a>(a: &'a i32, b: &i32) -> &'a i32 { a }

I want to keep a pointer to this function in a structure:

struct S {
    f: fn(a: &i32, b: &i32) -> &i32,
}

Since there are two input lifetimes, the lifetime of the result cannot be inferred:

error[E0106]: missing lifetime specifier
  |
2 |     f: fn(a: &i32, b: &i32) -> &i32,
  |                                ^ expected lifetime parameter
  |
  = help: this function return type contains a borrowed value,
    but the signature does not say whether it is borrowed from a or b

When I ask the compiler for a type foo, this is also not very useful:

let () = foo;

gives me

expected type `fn(&'a i32, &i32) -> &'a i32 {foo}`

which obviously does not work because it is 'anot defined anywhere.

So how do I declare life in this context? Try one of

f: fn<'a>(a: &'a i32, b: &i32) -> &'a i32
f<'a>: fn(a: &'a i32, b: &i32) -> &'a i32

leads to a syntax error, and I could not find the documentation describing this particular situation.

+4
source share
1 answer

:

fn foo<'a>(a: &'a i32, b: &i32) -> &'a i32 { a }

struct S<'b, 'c> {
    f: fn(a: &'b i32, b: &'c i32) -> &'b i32,
}

fn main() {
    S {
        f: foo,
    };
}

, .

, (s.f)(&x, &y) a b, foo(&x, &y)

(HRTB):

fn foo<'a>(a: &'a i32, _b: &i32) -> &'a i32 { a }

struct S<F>
    where for <'b, 'c> F: Fn(&'b i32, &'c i32) -> &'b i32,
{
    f: F,
}

fn main() {
    S {
        f: foo,
    };
}
+2

Source: https://habr.com/ru/post/1665409/


All Articles