以下是代码:
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))
}
}
U
引用时编译失败:
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
| +
我尝试引入一个通用的生命周期'a
但Foo::map_ref
不知道下一步该做什么。