I have a struct with multiple vectors and I want to change one of them while iterating over the other.
Let's say I iterate over the vector code
and change the vector data
of my Test
struct.
If I change the data in a function (change_data
), I don't have a problem; but if I create a method to the Test
struct with the same functionality, the compilation fails because I try to borrow the whole struct to the method.
Is there a way to create a method that changes data
while iterating over code
?
struct Test{
code: Vec<u8>,
data: Vec<u8>,
}
impl Test {
#[allow(dead_code)]
fn change_data(&mut self, index: usize, value: u8) {
self.data[index]=value;
}
}
#[allow(dead_code)]
fn change_data(data: &mut Vec<u8>, index: usize, value: u8) {
data[index]=value;
}
fn main() {
let mut test = Test{code: vec![1,2,3], data: vec![11,12,13]};
for (i,c) in test.code.iter().enumerate() { // (Bad alternative: No error if I insert `.clone()` after code)
//~ test.change_data(i,*c); // error[E0502]: cannot borrow `test` as mutable because it is also borrowed as immutable
change_data(&mut test.data, i, *c);
}
println!("{:?}", test.data);
}
(Playground) Line 20 works, but line 19 doesn't work if you uncomment it.
I appreciate any help I can get, thank you!