《Rust编程之道》指出,在处理类型的值时,使用
我想要克隆一个引用计数的结构体,并将其转换为一个特质对象。使用
Rc::clone(&x)
而不是x.clone()
是惯用法,这样可以清楚地表明这不是您通常使用的clone
函数。我完全赞同这种做法,但在实践中却遇到了困难。我想要克隆一个引用计数的结构体,并将其转换为一个特质对象。使用
rc.clone()
可以完成此操作,但使用Rc::clone(&rc)
却不能。这对我来说有点奇怪。struct ListView {}
trait View {}
impl View for ListView {}
fn very_contrived_example() {
let list_view: Rc<ListView> = Rc::new(ListView {});
let mut views: Vec<Rc<dyn View>> = Vec::new();
// Using Rc::clone does not work:
// error[E0308]: mismatched types
//
// views.push(Rc::clone(&list_view));
// ^^^^^^^^^^ expected trait object `dyn View`, found struct `ListView`
//
// note: expected reference `&Rc<dyn View>`
// found reference `&Rc<ListView>`
// Using a cast works in this very contrived example, but has the
// disadvantage of moving `list_view`, for some reason, which is not
// acceptable in general:
// views.push(Rc::clone(&(list_view as Rc<dyn View>)));
// But invoking it using method syntax works fine, without a move:
views.push(list_view.clone());
}
Rc::clone(&x)
和 x.clone()
之间有什么区别?x.clone()
实际上调用了哪个函数?self
的类型是什么?我能直接调用它吗?
如何以惯用方式编写这段代码?