I am very new to rust and I'm struggling with the following code. From what I understand, this needs to be restructured somehow, but I don't know how.
Note that I can use an iterator instead of a for loop, but this is a simplified version of a bigger piece of code I'm working on where a loop is preferable to an iterator.
struct Rec {
num: i32,
}
fn modify(data: &mut Vec<Rec>) -> Vec<&mut Rec> {
let mut ret = Vec::<&mut Rec>::new();
for j in 0 .. 10 {
let mut rec = data.get_mut(j).unwrap(); //<- error is here
ret.push(rec);
}
ret
}
The error is:
error[E0499]: cannot borrow `*data` as mutable more than once at a time
--> src/main.rs:10:23
|
7 | fn modify<'a>(data: &'a mut Vec<Rec>) -> Vec<&'a mut Rec>{
| -- lifetime `'a` defined here
...
10 | let mut rec = data.get_mut(j).unwrap();
| ^^^^ `*data` was mutably borrowed here in the previous iteration of the loop
...
14 | ret
| --- returning this value requires that `*data` is borrowed for `'a`
There's 2 questions:
- How to I restructure this. I have no idea
- Why doesn't the borrow end at the end of the code block for the for loop?
I've seen other posts offering assistance but I'm too much of a newbie to understand the advice given. Any help will be appreciated.