我想在另一个结构中的数组中更改一个结构的值:
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
如何解决这个例子?
最佳答案
您可以使用额外的 mut
修复编译错误:
bar: &'a [&'a mut Bar]
到 bar: &'a mut [&'a mut Bar]
关于rust - 无法在数组中的 `&` 引用中可变地借用数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42753516/