This code
// No particular meaning, just MVCE extracted from larger program
pub fn foo(mut v: Vec<i32>) {
let x = &v[0];
for _ in [0, 1] {
if *x == 0 {
v[0] = 0;
}
}
}
fails to compile with
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> <source>:5:13
|
2 | let x = &v[0];
| - immutable borrow occurs here
3 | for _ in [0, 1] {
4 | if *x == 0 {
| -- immutable borrow later used here
5 | v[0] = 0;
| ^ mutable borrow occurs here
I would expect it to compile because lifetime of *x ends before mutable v[0] is created ?
Code compiles if I remove the for-loop:
/*for _ in [0, 1]*/ {
if *x == 0 {
v[0] = 0;
}
}
What is the reason of such behavior ?
loop, and in this case if theforis replaced by aloopand abreakis added inside the conditional the code will compile: play.rust-lang.org/…whileandforloops are desugared toloop, so the type of loop has no incidence on the borrow-checker; it's purely a matter of iterations.