Move in clone impl

Hi, as you can see below, Point struct implements Copy/Clone trait, but in the clone impl I move p to _pp then return p, why the compiler doesnot error out that p is moved to _pp, thx

fn main() {
  let p1 = Point{x:1,y:2};
   
  let p2 = p1;
  p2.test();

  p1.test();
}

#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

trait Test {
    fn test(&self);
}

impl Test for Point {
    fn test(&self) {
        println!("{:?}", self);
    }
}

impl Copy for Point {}

impl Clone for Point {
    fn clone(&self) -> Point {
        let p = Point{
            x: self.x+1,
            y: self.y+1,
        };
        let _pp = p;
        p
    }
}

The reason you don't get a use-after-move error is because assigning any Copy type to another variable will just copy the bits across and not logically move out of the old variable.

2 Likes

The documentation answers the exact question you have, and also it contains some guidelines this code violates currently.

3 Likes

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.