我想修改临时存储到另一个变量self
。在最后一步,我想所有的数据从变量复制到self
。
struct A {
x: i32,
}
impl A {
fn new() -> Self {
Self { x: 0 }
}
fn change(&mut self) {
let mut a = Self::new();
a.x += 1;
self = a; // How to copy data from a variable into self?
}
}
我得到的错误:
error[E0308]: mismatched types
--> src/lib.rs:14:16
|
14 | self = a; // How to copy data from a variable into self?
| ^
| |
| expected &mut A, found struct `A`
| help: consider mutably borrowing here: `&mut a`
|
= note: expected type `&mut A`
found type `A`
我曾尝试self = &a
和self = &mut a
,它没有工作。我应该如何将数据从self
在这一行复制到a
?
我知道我的例子不是最优的,因为我可以只写self.x += 1
。在我的整个项目,我有a
硬的计算方法,包括self
本身,所以我需要在最后一行复制严格。
您需要取消引用self
:
*self = a;
没有什么关于self
或事实,这是一个独特的方法。同样的事情是因为你所替换值的任何可变引用真实的。
也可以看看: