我有一个包含值的结构,并且我想获得一个可以对这个值进行操作的函数:
struct Returner {
val: i32,
}
impl<'a> Returner {
fn get(&'a self) -> Box<Fn(i32) -> i32> {
Box::new(|x| x + self.val)
}
}
这段代码编译失败:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:7:18
|
7 | Box::new(|x| x + self.val)
| ^^^^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime 'a as defined on the impl at 5:1...
--> src/main.rs:5:1
|
5 | impl<'a> Returner {
| ^^^^^^^^^^^^^^^^^
= note: ...so that the types are compatible:
expected &&Returner
found &&'a Returner
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<std::ops::Fn(i32) -> i32 + 'static>
found std::boxed::Box<std::ops::Fn(i32) -> i32>
这是因为闭包借用了
self
,这对我来说没问题,因为我不打算在结构体被销毁后使用获得的函数。据我所知,有两种方法可以实现:
使用
move
关键字。但我不想使用它,因为它会占有该对象,并且我想在返回此函数后继续使用它。显式指定闭包的生命周期,以告诉编译器它与调用它的结构体具有相同的生命周期。
<'a>
应该修饰get
而不是impl
? - Matthieu M.'a
在其他地方并没有出现,但这确实是错误的量词使用位置。 - user395760