【发布时间】:2019-02-05 21:26:30
【问题描述】:
我正在尝试修改临时存储到另一个变量中的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,但没有成功。我应该如何将这一行中的a中的数据复制到self?
我知道我的例子不是最优的,因为我可以写self.x += 1。在我的完整项目中,我对 a 进行了艰苦的计算,其中包括 self 本身,因此我需要严格复制到最后一行。
【问题讨论】: