不能在数组中的`&`引用中可变地借用数据

时间:2017-03-12 21:40:14

标签: rust mutable

我想在另一个结构中更改数组中结构的值:

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;
    }
}

这会出错:

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

如何修复此示例?

1 个答案:

答案 0 :(得分:2)

您可以使用其他mut修复编译错误:

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