我有一个简单的链表类型和 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()
,它可以正常工作,但我不明白为什么 . MyClone
和 Clone
特征是相同的,所以在我看来他们会接受相同的实现 .
(我正在用rustc 0.12.0-nightly编译(72841b128 2014-09-21 20:00:29 0000) . )
1 回答
这是因为rust还具有Clone for
Box<T>
的实现 . 如果你为它实现MyClone
,那将是预期的owrk .