I checked out similar topics but i failed to address the issue. Blow i construed a small example that emulates what i have in reality.
#[derive(Debug, Clone)]
struct Y {
pub a: (usize, usize),
pub b: f32,
}
#[derive(Debug, Clone)]
struct X {
xx: Vec<Y>,
}
impl X {
pub fn new() -> Self {
X { xx: Vec::new() }
}
fn add(&mut self, x: Y) -> &mut Self {
self.xx.push(x);
self
}
fn pr(&self, x: &str) -> String {
x.to_string()
}
}
fn main() {
// new X object
let mut xx = X::new();
// fill X
xx.add(Y { a: (3, 7), b: 7.6 })
.add(Y { a: (37, 8), b: 2.6 });
// call mut since the for loop later does some changes
// but it also calls other methods that need to be executed
for _i in xx.xx.iter_mut() {
println!("{:?}", xx.pr("cc"))
}
}
Error naturally is:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `xx` as immutable because it is also borrowed as mutable
--> src/main.rs:34:26
|
33 | for _i in xx.xx.iter_mut() {
| ----------------
| |
| mutable borrow occurs here
| mutable borrow later used here
34 | println!("{:?}", xx.pr("cc"))
| ^^ immutable borrow occurs here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `playground` (bin "playground") due to previous error
How do i bypass this issue? I need the object X to be mutable as the elements within the array are subject to change in my for loop but i also need the access to the methods within X that contain recipes on how this should be changed (changes depend on outside factors)
any advice ??
Thank you