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没有成功.
Run Code Online (Sandbox Code Playgroud)fn add_assign(&mut self, other: &Self)
你的要求是不可能的.
您不能同时具有可变引用和对同一值的不可变引用.这是Rust的一个基本方面.
请重新阅读参考规则.
也可以看看:
Run Code Online (Sandbox Code Playgroud)fn add_assign(&mut self, other: Self)
你的要求是不可能的.
您需要一个struct实例A来调用方法,另一个实例A作为参数传递.您的类型未实现Copy或Clone提供任何等效方法,因此无法获取第二个实例.
除此之外,没有通用的方法可以对值进行可变引用并从中获取自有值.
也可以看看:
如果您实现Copy或Clone,那么您可以从原始版本获取第二个值,然后调用您的任一版本.
如果您实施Copy:
(other: Self)
self.add_assign(*self);
Run Code Online (Sandbox Code Playgroud)(other: &Self)
let other = *self;
self.add_assign(&other);
Run Code Online (Sandbox Code Playgroud)如果只有Clone:
(other: Self)
self.add_assign(self.clone());
Run Code Online (Sandbox Code Playgroud)(other: &Self)
self.add_assign(&self.clone());
Run Code Online (Sandbox Code Playgroud)您可能希望实现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)
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |