I'm attempting to mutate a struct that is a member of a vector within another struct. Despite reading the documentation and many, many articles on ownership, I'm still obviously missing something because I cannot get the following, relatively trivial code to work.
I'm getting a compiler error on the line add_content(&mut bar); which says cannot borrow data in a '&' reference as mutable, which I know is true, but I cannot figure how to get it to work.
I've been reading about Box<T>, Cell<T> and RefCell<T> and wondering if I might need to make use of one of those but I'm very unfamiliar with them and it seems like my trivial example below should work without extra complications.
#[derive(Debug)]
struct Foo {
id: u32,
bars: Vec<Bar>,
}
#[derive(Debug)]
struct Bar {
id: u32,
content: String,
}
fn main() {
let mut foos: Vec<Foo> = Vec::new();
foos.push(Foo {
id: 100,
bars: Vec::new(),
});
foos[0].bars.push(Bar {
id: 200,
content: String::new(),
});
loops(&foos);
println!("{:#?}", foos);
}
fn loops(foos: &Vec<Foo>) {
for foo in foos {
for mut bar in &foo.bars {
add_content(&mut bar);
}
}
}
fn add_content(bar: &mut Bar) {
bar.content = String::from("hello");
}
Note that my example is deliberately trivial. My actual program is more involved but I've tried to boil down the problem to just the part that's giving me a headache.
How can I get the above code to work?