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

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);
主站蜘蛛池模板: 长兴县| 佳木斯市| 邢台县| 兖州市| 鲜城| 通许县| 莲花县| 晋州市| 湘乡市| 林芝县| 平阳县| 建始县| 乌兰浩特市| 日照市| 榆中县| 康保县| 桑植县| 万源市| 旺苍县| 松潘县| 叶城县| 丹凤县| 秦安县| 衡阳市| 东乌珠穆沁旗| 南岸区| 炎陵县| 泰安市| 武平县| 阿尔山市| 犍为县| 永和县| 将乐县| 马龙县| 东阿县| 竹北市| 兖州市| 普兰县| 迁西县| 阿拉尔市| 津南区|