0

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.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95

1 Answers1

5

You need to dereference self:

*self = a;

There's nothing unique about self or the fact that this is a method. The same thing is true for any mutable reference where you are replacing the value.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366