10

I want to change a value of a struct in an array in another struct:

struct Foo<'a> {
    bar: &'a [&'a mut Bar]
}

struct Bar {
    baz: u16
}

impl<'a> Foo<'a> {
    fn add(&mut self, x: u16) {
        self.bar[0].add(x);
    }
}

impl Bar {
    fn add(&mut self, x: u16) {
        self.baz += x;
    }
}

This gives an error:

error[E0389]: cannot borrow data mutably in a `&` reference
  --> src/main.rs:11:9
   |
11 |         self.bar[0].add(x);
   |         ^^^^^^^^^^^ assignment into an immutable reference

How would one fix this example?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Charlie
  • 978
  • 1
  • 7
  • 27

1 Answers1

8

You can fix compilation error with additional mut:

bar: &'a [&'a mut Bar] to bar: &'a mut [&'a mut Bar]

fghj
  • 8,898
  • 4
  • 28
  • 56