我想在另一个结构中更改数组中结构的值:
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
如何修复此示例?
答案 0 :(得分:2)
您可以使用其他mut
修复编译错误:
bar: &'a [&'a mut Bar]
至bar: &'a mut [&'a mut Bar]