Rust的Copy和Clone

Rust Trait: Copy和Clone

简单记录下对Copy和Clone的理解

未实现Clone, 移动语义

下面的例子中, 第13行打印u时报错, 是因为u被移动到了another_u, u的值被释放了

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#[derive(Debug)]
#[allow(unused)]
struct User {
    age: i32
}

fn main() {
    let u: User = User{
        age: 25
    };
    println!("{:?}",u);
    let another_u = u;
    println!("{:?}",u);
}

编译报错信息如下, 提示我们User没有实现Copy这个trait, 第13行借用了第12行中已经移动了的u 还提示可以实现 Clone trait

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
error[E0382]: borrow of moved value: `u`
  --> src\main.rs:13:21
   |
8  |     let u: User = User{
   |         - move occurs because `u` has type `User`, which does not implement the `Copy` trait
...
12 |     let another_u = u;
   |                     - value moved here
13 |     println!("{:?}",u);
   |                     ^ value borrowed here after move
   |
note: if `User` implemented `Clone`, you could clone the value
  --> src\main.rs:3:1
   |
3  | struct User {
   | ^^^^^^^^^^^ consider implementing `Clone` for this type
...
12 |     let another_u = u;
   |                     - you could clone this value
   = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

实现 Clone

实现Clone trait之后, 可以显式调用clone()方法来进行深拷贝

提示

如果所有字段都实现了Clone, 那么#[derive(Clone)]会自动实现Clone trait

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#[derive(Debug,Clone)]
#[allow(unused)]
struct User {
    age: i32
}

fn main() {
    let u: User = User{
        age: 25
    };
    println!("{:?}",u);
    let another_u = u.clone();
    println!("{:?}",u);
    println!("{:?}",another_u);
}

实现 Copy, 按bits复制, 非移动语义

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#[derive(Debug,Clone,Copy)]
#[allow(unused)]
struct User {
    age: i32
}

fn main() {
    let u: User = User{
        age: 25
    };
    println!("{:?}",u);
    let another_u = u;
    println!("{:?}",u);
    println!("{:?}",another_u);
}

编译成功, 正常执行

User { age: 25 }
User { age: 25 }
User { age: 25 }

其他

Copy是按位做浅拷贝,那么它会默认拷贝的数据没有需要释放的资源;而Drop恰恰是为了释放额外的资源而生的

0%