无法在数组的`&`引用中可变地借用数据 [英] Cannot borrow data mutably in a `&` reference in array

查看:68
本文介绍了无法在数组的`&`引用中可变地借用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这给出了一个错误:

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修复编译错误:

You can fix compilation error with additional mut:

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

这篇关于无法在数组的`&amp;`引用中可变地借用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆