Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my implicitly Copyable variable being moved?

Tags:

rust

According to the Rust reference at the time of this writing:

For types that contain owning pointers or values that implement the special trait Drop, the variable is moved. All other types are copied.

Below is my code. I will expect Point to be a copyable type. But it is getting moved and the following code will not compile with 0.13.0-nightly.

struct Point {
    x: uint,
    y: uint
}

fn main() {
    let p: Point = Point{x: 10u, y: 10u};

    let p1 = p;
    let p2 = p; //Error: p has been moved p1
}

The compile error states:

note: `p` moved here because it has type `Point`, which is moved by default

Why is Point not treated as a copyable type?

like image 769
RajV Avatar asked Dec 26 '22 00:12

RajV


1 Answers

Copy must now be added explicitly, guide was just not updated yet:

#[derive(Copy)]
struct Point {
    x: uint,
    y: uint
}

fn main() {
    let p: Point = Point{x: 10u, y: 10u};

    let p1 = p;
    let p2 = p; // Now works because it is Copy.
}
like image 51
Arjan Avatar answered Dec 30 '22 13:12

Arjan