如何将对self的可变引用转换为不可变引用以用作方法的参数?

Fom*_*aut -1 methods reference immutability rust

我有以下无法编译的代码:

struct A {
    x: i32,
}

impl A {
    fn add_assign(&mut self, other: &Self) {
        self.x += other.x;
    }

    fn double(&mut self) {
        self.add_assign(self);
    }
}
Run Code Online (Sandbox Code Playgroud)

错误是:

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
  --> src/lib.rs:11:9
   |
11 |         self.add_assign(self);
   |         ^^^^^----------^----^
   |         |    |          |
   |         |    |          immutable borrow occurs here
   |         |    immutable borrow later used by call
   |         mutable borrow occurs here
Run Code Online (Sandbox Code Playgroud)

如何传递self作为参数add_assign?我已经试过&self,*self,&*self没有成功.

She*_*ter 6

对于当前版本的问题

fn add_assign(&mut self, other: &Self)
Run Code Online (Sandbox Code Playgroud)

你的要求是不可能的.

您不能同时具有可变引用和对同一值的不可变引用.这是Rust的一个基本方面.

请重新阅读参考规则.

也可以看看:

对于第一个版本的问题

fn add_assign(&mut self, other: Self)
Run Code Online (Sandbox Code Playgroud)

你的要求是不可能的.

您需要一个struct实例A来调用方法,另一个实例A作为参数传递.您的类型未实现CopyClone提供任何等效方法,因此无法获取第二个实例.

除此之外,没有通用的方法可以对值进行可变引用并从中获取自有值.

也可以看看:

解决方法

如果您实现CopyClone,那么您可以从原始版本获取第二个值,然后调用您的任一版本.

如果您实施Copy:

如果只有Clone:

您可能希望实现AddAssign特征以提供语法糖.Assolangn你已经实施Copy:

impl A {
    fn double(&mut self) {
        *self += *self;
    }
}

impl std::ops::AddAssign<Self> for A {
    fn add_assign(&mut self, other: Self) {
        self.x += other.x;
    }
}
Run Code Online (Sandbox Code Playgroud)

Stargateur的评论也可能适用于i32实施Copy:

impl A {
    fn double(&mut self) {
        *self += self.x;
    }
}

impl std::ops::AddAssign<i32> for A {
    fn add_assign(&mut self, other: i32) {
        self.x += other;
    }
}
Run Code Online (Sandbox Code Playgroud)