Ownership in mutable references to self

I am struggling to understand how ownership works. I have this example:

struct MyStruct {
  data: Vec<Box<dyn MyTrait>>
  ...
}

impl MyStruct {
  fn change_vector(&mut self) {
    for i in 0..self.data.len() {
      let mut example = &data[i];
      example.some_mutating_function();
    }
  }
  ...
}

Which then leads to the error: "data" is a "&" reference, so the data it refers to cannot be borrowed as mutable

What is the correct pattern for iterating over a vector and running functions that mutate the structs within?

Perhaps you wanted &mut data[i]?

1 Like

Try this one. Using Iterator instead of manual indexing is not just more idiomatic but also generally more performent as it explicitly skip the bound check.

impl MyStruct {
  fn change_vector(&mut self) {
    for example in &mut self.data {
      example.some_mutating_function();
    }
  }
  ...
}
2 Likes

@cuviper @Hyeonu
Thank you both for the quick replies. Both solutions seem to work perfectly. I thought I had tried &mut data[i], but I guess I was wrong.

I also stumbled across a Reddit thread about iter_mut() which also functions well.