Im trying to understand why borrow checker complains in one instance while it doesnt in another.
fn main() {
let mut v1 = vec![1,2,3];
for i in 0..3 {
let mut v2 = v1.drain(..);
println!("{:?}", v2);
v1= vec![1,2,3];
}
println!("Done!");
}
In above piece of code I get
error[E0506]: cannot assign to `v1` because it is borrowed
--> src/main.rs:8:9
|
6 | let mut v2 = v1.drain(..);
| -- borrow of `v1` occurs here
7 | println!("{:?}", v2);
8 | v1= vec![1,2,3];
| ^^ assignment to borrowed `v1` occurs here
9 | }
| - borrow might be used here, when `v2` is dropped and runs the `Drop` code for type `std::vec::Drain`
My thinking: Since v2
is dropped at end of for
loop, it might require v1
that it borrowed to do something before it gets dropped. The last line of error is pretty clear on that. Hence, this is not allowed.
But below runs fine
fn main() {
let mut v1 = Some(vec![1,2,3]);
for i in 0..3 {
if v1.is_some() {
let v1_take = v1.take();
let mut v2 = v1_take.unwrap();
println!("{:?}", v2);
v1 = Some(vec![1,2,3]);
}
}
println!("Done!");
}
Now take()
also borrows v1
mutably just like drain()
did for previous example. So why dont I get similar error? Does compiler think "v1 can reassigned because it has None
anyways"?