Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot borrow data mutably in a `&` reference in array

Tags:

mutable

rust

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?

like image 708
Charlie Avatar asked Apr 08 '26 00:04

Charlie


1 Answers

You can fix compilation error with additional mut:

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

like image 199
fghj Avatar answered Apr 12 '26 01:04

fghj