Mon*_*nth 4 closures lifetime rust
我有一个包含值的结构,我想获得一个对该值进行操作的函数:
struct Returner {
val: i32,
}
impl<'a> Returner {
fn get(&'a self) -> Box<Fn(i32) -> i32> {
Box::new(|x| x + self.val)
}
}
Run Code Online (Sandbox Code Playgroud)
编译失败:
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>
Run Code Online (Sandbox Code Playgroud)
这是因为闭包借用了self,这对我很好,因为在构造被销毁之后我不打算使用获得的函数.从我到目前为止收集的内容来看,有两种方法可以实现:
使用move关键字.我不想使用它,因为它将取得对象的所有权,并希望我在返回此函数后使用它.
显式指定闭包的生命周期,告诉编译器它与调用它的结构具有相同的生命周期.
我认为2在我的情况下是正确的方法,但我无法找到如何指定闭包的生命周期.有没有直接的方法来做到这一点,或者我已经把它弄错了,它与Rust的生命逻辑相矛盾?
小智 8
通常,您可以通过写入来指定盒装特征对象的生命周期,Box<Trait + 'a>并且类似地为其他类型的指针后面的特征对象指定(如果省略它,则默认为'static至少在这种情况下Box).因此,在这种特定情况下,您需要返回类型Box<(Fn(i32) -> i32) + 'a>.
但是,当你这样做时,你会看到另一个关于self不能长寿的错误.原因是(没有move)闭包将捕获对局部变量的引用self.解决方案是使用move.此不移动Returner物体,它移动self这是一个参考的Returner对象.
综上所述:
struct Returner {
val: i32,
}
impl<'a> Returner {
fn get(&'a self) -> Box<Fn(i32) -> i32 + 'a> {
Box::new(move |x| x + self.val)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |