rust clone 的一个小注意点

先看代码A:

#[derive(Debug, Clone)]
struct Test(i32);

fn main() {
    let mut x = Test(1);
    let a = &x;
    let b = a.clone();
    let c: i32 = b;
}

这段代码报的错是:

  |
8 |     let c: i32 = b;
  |                  ^ expected i32, found struct `Test`
  |
  = note: expected type `i32`
             found type `Test`

再看代码B:

#[derive(Debug)]
struct Test(i32);

fn main() {
    let mut x = Test(1);
    let a = &x;
    let b = a.clone();
    let c: i32 = b;
}

报错是:

  |
8 |     let c: i32 = b;
  |                  ^ expected i32, found &Test
  |
  = note: expected type `i32`
             found type `&Test`

两段代码的唯一区别就是结构体Test,A实现Clone,B没有实现Clone。

结论就是:如果一个引用,它引用的对象如果不能clone,就clone引用,如果能clone,就直接clone对象并返回。

转载于:https://my.oschina.net/u/855913/blog/3072629

你可能感兴趣的:(rust clone 的一个小注意点)