I'm just learning Rust, and I've run across a problem I've reduced to the following minimal example:
#[derive(Debug)]
struct Foo {
num: i32,
}
impl Foo {
fn bar(mut self) -> Self {
self.num = self.num + 100;
self
}
}
fn main() {
let mut x = [Foo{num: 1}, Foo{num: 2}, Foo{num: 3}, Foo{num: 4}];
for n in &mut x {
*n = n.bar();
}
println!("{:?}", x);
}
This spits out the dreaded
error[E0507]: cannot move out of `*n` which is behind a mutable reference
Now, I know I could just change the signature of bar()
to take a mutable reference, but I don't want to do that for reasons. Likewise, I could use something functional -- probably using into_iter()
and map()
-- but I'd have to collect::<Vec<Foo>>()
or similar, and it doesn't make sense to me that an operation like this should have to return a dynamically-sized array.
It makes intuitive sense that I should be able to initialize an array of a statically-known size, consume each element, and replace it with another one to get an array of the same statically-known size. I just don't know how to express this in a properly Rust-y fashion.