[英]Mimicking the Clone trait in Rust
我有一个简单的链表类型和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,
}
}
}
它按预期工作。 但是如果我使用与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)。)
这是因为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,
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.