I know the general answer — You can only borrow mutably once or immutably many times, but not both. I want to know why this specific case is considered simultaneous borrowin
If so, surely the compiler could improve this...right?
Indeed, NLL intentionally started conservatively, as explained in #494341.
Extracting the temporary allows it to compile:
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let n = 3;
// checks on n and v.len() and whatever else...
let s = v[..n].to_vec();
for i in 0..n {
let index = i + v.len() - n;
v[index] = s[1];
}
}
This makes it clear that the issue is strictly one of not computing the index before attempting to use it.
Since it is not possible to start the call to IndexMut
before computing the Idx
, there is no reason to start the mutable borrow of v
before computing the index.
1 Courtesy of trentcl.