如何将可变引用自转换为不可变的引用被用作方法的参数?第一个版本

问题描述 投票:-1回答:1

我有以下不能编译的代码:

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

错误是:

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

如何通过q​​azxswpoi作为self的说法?我曾尝试add_assign&self*self没有成功。

methods reference rust immutability
1个回答
6
投票

For the current version of the question

&*self

您的要求是不可能的。

你不能有一个可变的引用,并在同一时间不变参考值相同。这是铁锈的一个基本方面。

请重新阅读fn add_assign(&mut self, other: &Self)

也可以看看:

For the Cannot borrow as mutable because it is also borrowed as immutable of the question

first version

您的要求是不可能的。

你需要结构fn add_assign(&mut self, other: Self) 的一个实例来调用方法和A的另一个实例作为参数传递。你的类型不实现ACopy或提供任何等同方法,所以没有办法得到一个第二个实例。

除此之外,还有采取了可变参考值,并得到一个拥有值超出它没有普遍的方式。

也可以看看:

  • Clone

Workarounds

如果要实现Cannot move out of borrowed contentCopy,那么你可以从原来的第二值,然后打电话或者您的版本。

如果您实施Clone

  • Copy (other: Self)
  • self.add_assign(*self); (other: &Self)

如果只有let other = *self; self.add_assign(&other);

  • Clone (other: Self)
  • self.add_assign(self.clone()); (other: &Self)

你可能想实现self.add_assign(&self.clone()); 性状提供语法糖。 Assuminngn你已经实现AddAssign

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; } } 也可以适用,因为Stargateur's comment实现i32

Copy
© www.soinside.com 2019 - 2024. All rights reserved.