0

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.

Reid Rankin
  • 1,078
  • 8
  • 26
  • Your function is not functional anyway so – Stargateur Mar 08 '20 at 20:33
  • @Stargateur The compiler can infer the precise size of the source array from the literal, but I'd have to hardcode it in the array type I'm collecting to and that's not very DRY. – Reid Rankin Mar 08 '20 at 20:39
  • And you don't want to use a vector because ? Best I can propose you with information you give is https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=81f060a4bebeb5fa4e5a58385d05cb72. Also, array in rust are special like in C. Being able to create an array in runtime would create more problem than just use good old vector. – Stargateur Mar 08 '20 at 20:41

0 Answers0