我有一个简单的链表类型和它的实现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,
}
}
}
Run Code Online (Sandbox Code Playgroud)
它按预期工作.但是,如果我做我自己的MyClone特质与
相同签名
作为的Clone,我得到一个错误:
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()),
Run Code Online (Sandbox Code Playgroud)
如果我改变它box rest.my_clone(),它工作正常,但我不明白为什么.在MyClone和Clone特点是相同的,所以在我看来,他们将接受相同的实现.
(我正在用rustc 0.12.0-nightly编译(72841b128 2014-09-21 20:00:29 +0000).)
这是因为锈也有克隆的实现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,
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
479 次 |
| 最近记录: |