官术网_书友最值得收藏!

  • Rust Programming By Example
  • Guillaume Gomez Antoni Boucher
  • 168字
  • 2021-07-02 19:12:58

Copy types

Some types are not moved when we assigned a value of these types to another variable. This is the case for basic types such as integers. For instance, the following code is perfectly valid:

let num1 = 42;
let num2 = num1;
println!("{}", num1);

We can still use num1 even thought we assigned it to num2. This is because the basic types implement a special marker: Copy. Copy types are copied instead of moved.

We can make our own types Copy by adding derive to them:

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

Since Copy requires Clone, we also implement the latter for our Point type. We cannot derive Copy for a type containing a value that does not implement Copy. Now, we can use a Point without having to bother with references:

fn print_point(point: Point) {
    println!("x: {}, y: {}", point.x, point.y);
}

let p1 = Point { x: 1, y: 2 };
let p2 = p1;
print_point(p1);
println!("{}", p1.x);
主站蜘蛛池模板: 贞丰县| 永州市| 北安市| 云林县| 三门县| 西华县| 阳东县| 博湖县| 巧家县| 永寿县| 彭州市| 江油市| 星子县| 漳浦县| 扶余县| 孟连| 菏泽市| 清丰县| 辽阳县| 玛曲县| 广宁县| 海宁市| 峨边| 通州市| 大厂| 镇江市| 班戈县| 太仆寺旗| 新丰县| 宣威市| 辽宁省| 综艺| 锦屏县| 徐水县| 余江县| 崇仁县| 桂东县| 乌兰察布市| 嘉义市| 万年县| 楚雄市|