考虑以下 Rust 代码:
fn foo<'a, T, F, G>(x: &'a mut T, f: F, g: G)
where
T: 'a,
F: Fn(&'a T) -> &'a T,
G: Fn(&'a mut T) -> &'a mut T,
{
{
f(x);
}
g(x);
}
fn main() {
let mut x = 5;
foo(&mut x, |a| a, |a| a);
}
这会导致编译器错误:
error[E0502]: cannot borrow `*x` as mutable because it is also borrowed as immutable
--> src/main.rs:10:7
|
8 | f(x);
| - immutable borrow occurs here
9 | }
10 | g(x);
| ^ mutable borrow occurs here
11 | }
| - immutable borrow ends here
我不明白为什么在第11行不可变的借用x
会结束。首先,f(x)
在一个内部范围内,该范围在第9行结束。但是,f(x)
的返回值没有绑定到任何变量,因此我认为借用应该在第8行结束,而内部范围甚至不必要。