I am trying to modify self
that temporarily is stored into another variable. At the last step I want to copy all the data from the variable into 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?
}
}
I get the error:
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`
I have tried self = &a
and self = &mut a
, it didn't work. How am I supposed to copy the data into self
from a
in this line?
I know that my example is not optimal because I could just write self.x += 1
. In my complete project, I have hard calculations with a
that include self
itself so I need to copy in the last line strictly.