Aqui está o código:
fn main() {
let foo: Foo<i32> = Foo(42);
let bar: Foo<i64> = foo.map_ref(|x| *x as i64); // OK
let baz: Foo<&i32> = foo.map_ref(|x| x); // Error
}
struct Foo<T>(T);
impl<T> Foo<T> {
fn map_ref<U, F>(&self, f: F) -> Foo<U>
where
F: Fn(&T) -> U,
{
Foo(f(&self.0))
}
}
Falha ao compilar quando U
é referência:
error: lifetime may not live long enough
--> src\main.rs:4:48
|
4 | let baz: Foo<&i32> = foo.map_ref(|x: &i32| x); // Error
| - - ^ returning this value requires that `'1` must outlive `'2`
| | |
| | return type of closure is &'2 i32
| let's call the lifetime of this reference `'1`
|
help: dereference the return value
|
4 | let baz: Foo<&i32> = foo.map_ref(|x: &i32| *x); // Error
| +
Tentei introduzir um tempo de vida genérico 'a
e Foo::map_ref
não tenho ideia do que fazer a seguir.