相关疑难解决方法(0)

不能借用为不可变的因为它在函数参数中也被借用为可变的

这里发生了什么(游乐场)?

struct Number {
    num: i32
}

impl Number {
    fn set(&mut self, new_num: i32) {
        self.num = new_num;
    }
    fn get(&self) -> i32 {
        self.num
    }
}

fn main() {
    let mut n = Number{ num: 0 };
    n.set(n.get() + 1);
}
Run Code Online (Sandbox Code Playgroud)

给出了这个错误:

error[E0502]: cannot borrow `n` as immutable because it is also borrowed as mutable
  --> <anon>:17:11
   |
17 |     n.set(n.get() + 1);
   |     -     ^          - mutable borrow ends here
   |     |     |
   |     | …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

21
推荐指数
1
解决办法
3400
查看次数

为什么在涉及 += 运算符的同一表达式中使用可变引用和不可变引用有时似乎是允许的,有时却是不允许的?

在下面的代码示例中,我试图以四种不同的方式通过a对结构X的可变引用来增加结构的成员变量。在这里,编译器为由 表示的行给出以下错误B

error[E0502]: cannot borrow `*x` as immutable because it is also borrowed as mutable
  --> src\main.rs:17:23
   |
17 |     *x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
   |     ------------------^--------
   |     ||                |
   |     ||                immutable borrow occurs here
   |     |mutable borrow occurs here
   |     mutable borrow later used here
Run Code Online (Sandbox Code Playgroud)

如果是使用可变和不可变的参照问题a在同一个表达式,为什么CD编译?

struct X {
    a: i64,
}

impl X {
    pub fn get_a_mut(&mut self) -> &mut i64 {
        return &mut …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker

2
推荐指数
1
解决办法
66
查看次数

标签 统计

borrow-checker ×2

rust ×2