首页 文章

在Rust中模仿克隆特征

提问于
浏览
3

我有一个简单的链表类型和 Clone 的实现:

#[deriving(Show)]
enum List {
    Cons(int, Box<List>),
    Nil,
}

impl Clone for List {
    fn clone(&self) -> List {
        match *self {
            Cons(val, ref rest) => Cons(val, rest.clone()),
            Nil => Nil,
        }
    }
}

它按预期工作 . 但是,如果我使用the same signature作为 Clone 创建自己的 MyClone 特征,我会收到错误:

trait MyClone {
    fn my_clone(&self) -> Self;
}

impl MyClone for List {
    fn my_clone(&self) -> List {
        match *self {
            Cons(val, ref rest) => Cons(val, rest.my_clone()),
            Nil => Nil,
        }
    }
}

.../src/main.rs:23:46: 23:61 error: mismatched types: expected `Box<List>`, found `List` (expected box, found enum List)
.../src/main.rs:23             Cons(val, ref rest) => Cons(val, rest.my_clone()),

如果我将其更改为 box rest.my_clone() ,它可以正常工作,但我不明白为什么 . MyCloneClone 特征是相同的,所以在我看来他们会接受相同的实现 .

(我正在用rustc 0.12.0-nightly编译(72841b128 2014-09-21 20:00:29 0000) . )

1 回答

  • 5

    这是因为rust还具有Clone for Box<T> 的实现 . 如果你为它实现 MyClone ,那将是预期的owrk .

    #[deriving(Show)]
    enum List {
        Cons(int, Box<List>),
        Nil,
    }
    
    trait MyClone {
        fn my_clone(&self) -> Self;
    }
    
    impl<T: MyClone> MyClone for Box<T> {
        fn my_clone(&self) -> Box<T> {
            self.my_clone()
        }
    }
    
    impl MyClone for List {
        fn my_clone(&self) -> List {
            match *self {
                Cons(val, ref rest) => Cons(val, rest.my_clone()),
                Nil => Nil,
            }
        }
    }
    

相关问题