当我尝试使用Rust闭包时,遇到了一个有趣的场景:
fn main() {
let mut y = 10;
let f = || &mut y;
f();
}
这会导致一个错误:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:4:16
|
4 | let f = || &mut y;
| ^^^^^^
|
note: first, the lifetime cannot outlive the lifetime as defined on the body at 4:13...
--> src/main.rs:4:13
|
4 | let f = || &mut y;
| ^^^^^^^^^
note: ...so that closure can access `y`
--> src/main.rs:4:16
|
4 | let f = || &mut y;
| ^^^^^^
note: but, the lifetime must be valid for the call at 6:5...
--> src/main.rs:6:5
|
6 | f();
| ^^^
note: ...so type `&mut i32` of expression is valid during the expression
--> src/main.rs:6:5
|
6 | f();
| ^^^
尽管编译器正在逐行解释,但我仍然不明白它到底在抱怨什么。
它是在说可变引用不能超出封闭的闭包吗?
如果我删除调用f()
,编译器就不会抱怨。
struct
形式? - soupybionics