Can I move a non-Copy if I replace it?

Hello,

Can I move a value to a different field without cloning it, if I overwrite the original one? Consider:

struct TwoValues {
  previous: String,
  current: String
}
impl TwoValues {
  fn push(&mut self, next: String) -> () {
    self.previous = self.current.clone();  //  Can I get rid of this clone?
    self.current = next;
  }
}

This won't compile without the clone(), because it would move a filed. Can I get rid of the clone by replacing the value in the same step? Thanks!

Best, Oliver

You can use core::mem::replace.

impl TwoValues {
  fn push(&mut self, next: String) -> () {
    let current = core::mem::replace(&mut self.current, next);
    self.previous = current;
  }
}
1 Like

Exactly what I was looking for, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.