There are a lot of answers for the questions about Rust's error[E0502], but I can't really understand one particular case. I have a struct and it's impl method that goes like this:
struct Test {
test_vec: Vec<i32>,
}
impl Test {
// other methods...
fn test(&mut self) -> i32 {
self.test_vec.swap(0, self.test_vec.len() - 1);
// other operations...
}
}
Trying to compile that immediately results in error:
error[E0502]: cannot borrow
self.test_vecas immutable because it is also borrowed as mutable
self.test_vec.swap(0, self.test_vec.len() - 1);
------------- ---- ^^^^^^^^^^^^^ immutable borrow occurs here
| |
| mutable borrow later used by call
mutable borrow occurs here
Can anyone please explain why? It doesn't really look like I'm trying to borrow self.test_vec there, I'm passing the usize type result of a len() call. On the other hand:
fn test(&mut self) -> i32 {
let last_index = self.test_vec.len() - 1;
self.test_vec.swap(0, last_index);
// other operations...
}
Using temporary variable, it works as expected, makes me thinking that len() call is somehow evaluated after it gets to to the swap, and thus being borrowed? Am I not seeing something because of the syntax sugar?