我有以下不能编译的代码:
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
如何通过qazxswpoi作为self
的说法?我曾尝试add_assign
,&self
,*self
没有成功。
&*self
您的要求是不可能的。
你不能有一个可变的引用,并在同一时间不变参考值相同。这是铁锈的一个基本方面。
请重新阅读fn add_assign(&mut self, other: &Self)
。
也可以看看:
first version
您的要求是不可能的。
你需要结构fn add_assign(&mut self, other: Self)
的一个实例来调用方法和A
的另一个实例作为参数传递。你的类型不实现A
或Copy
或提供任何等同方法,所以没有办法得到一个第二个实例。
除此之外,还有采取了可变参考值,并得到一个拥有值超出它没有普遍的方式。
也可以看看:
Clone
如果要实现Cannot move out of borrowed content或Copy
,那么你可以从原来的第二值,然后打电话或者您的版本。
如果您实施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