Rust笔记 - Clone trait

117 阅读1分钟

在Rust中实现Clone, 则可以通过该trait对变量进行深度复制。有的时候我们的确需要获取当前变量的副本而不是引用,可以通过实现该trait。下面看一下定义:

trait Clone: Sized {
    fn clone(&self) -> Self;
    fn clone_from(&mut self, source: &Self) {
        *self = source.clone()
    }
}

trait Copy: Clone { }

下面就实现一下该trait:

struct Any<T, U> {
    memb1: T,
    memb2: U,
}

impl<T, U> Clone for Any<T, U>
where T: Clone,
      U: Copy,
{
    fn clone(&self) -> Self {
        Any {
            memb1: self.memb1.clone(),
            memb2: self.memb2,
        }
    }
}

fn main() {
    let a = Any {
        memb1: "jack".to_string(),
        memb2: 32,
    };
    let b = a.clone();
    assert_eq!(a.memb1, b.memb1);
    assert_eq!(a.memb2, b.memb2);
}