借用 self 作为可变的和 self 的成员不可能吗?

Gat*_*ito 6 rust

struct State {
    x: i32
}

trait A {
    fn a(&mut self, b: &i32);
}

impl A for State {
    fn a(&mut self, b: &i32) {
        
    }
}

fn main() {
    let mut a = State{x: 0};
    a.a(&a.x);
}
Run Code Online (Sandbox Code Playgroud)

错误:

error[E0502]: cannot borrow `a` as mutable because it is also borrowed as immutable
  --> src/main.rs:17:5
   |
17 |     a.a(&a.x);
   |     ^^-^----^
   |     | | |
   |     | | immutable borrow occurs here
   |     | immutable borrow later used by call
   |     mutable borrow occurs here
Run Code Online (Sandbox Code Playgroud)

看起来错误涉及借用self,但我只借用 self 一次,第二次b应该是struct 成员的借用。

当我借用结构体的成员时,Rust 是否会完全借用该结构体?

我读了https://doc.rust-lang.org/nomicon/borrow-splitting.html,但它说只要不是切片,就可以借用结构体的一个元素。

Dmi*_*try 6

当您调用A::a方法时,它会借用其实现的整个变量。因此,您不能同时对同一对象(或其内容)进行不可变引用。

struct State {
    x: i32,
    y: i32,
}

trait A {
    fn a(&mut self, b: &i32); // borrow a whole `Self` always
}

impl A for State {
    fn a(&mut self, b: &i32) {
        // consider next code
        self.x *= 2 + *b;
        // if you provide `b` as `&a.x`, then it becomes unclear what result should be
    } // borrow a whole `Self` always
}

fn swap(first: &mut i32, second: &mut i32) {} // borrow only provided `i32`s

fn main() {
    let mut a = State{x: 0, y: 0};
    // a.a(&a.x); // you can't, as long as `a.a` borrows whole `State` 
    swap(&mut a.x, &mut a.y); // but you can borrow partially if the parts are separate
}
Run Code Online (Sandbox Code Playgroud)