Consider the following Rust code:
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);
}
This gives the compiler error:
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
I do not understand why the immutable borrow of x
ends on line 11. For one, f(x)
is in an inner scope which ends on line 9. However, the return value of f(x)
is not bound to any variable, so I would think the borrow should end on line 8, and the inner scope shouldn't even be necessary.