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.

1 Answer 1

6

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.