I'm trying to do something like this
struct Foo {
commands: Vec<String>,
}
impl Foo {
fn do_something(&self, _c: &mut String) {
//...
}
}
fn main() {
let mut foo = Foo {
commands: vec!["a".to_string(), "b".to_string()],
};
for command in foo.commands.iter_mut() {
foo.do_something(command);
}
println!("All done");
}
Rightfully so the compiler complains as I have a borrow on both foo
and commands
at the same time.
error[E0502]: cannot borrow `foo` as immutable because `foo.commands` is also borrowed as mutable
--> src/main.rs:17:9
|
16 | for command in foo.commands.iter_mut() {
| ------------ - mutable borrow ends here
| |
| mutable borrow occurs here
17 | foo.do_something(command);
| ^^^ immutable borrow occurs here
I found a way to work around this but I find it particularly inelegant yet I can't find another way
struct Foo {
commands: Vec<String>,
}
impl Foo {
fn do_something(&self, _c: &mut String) {
//...
}
}
fn main() {
let mut foo = Foo {
commands: vec!["a".to_string(), "b".to_string()],
};
let mut commands = Vec::new();
loop {
match foo.commands.pop() {
Some(command) => commands.push(command),
None => break,
}
}
for command in commands.iter_mut() {
foo.do_something(command);
}
println!("All done");
}
Is there a better way to do this? Thanks in advance for your help !!!
Playground links:
Top example
Bottom example (working yet inelegant)