如何在转换为trait对象时使用Rc::clone?
锈病书上说,它是地道的使用Rc::clone(&x),而不是x.clone()用Rc值,这样很明显,这不是典型的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什么?可以直接调用吗?
写这个的惯用方式是什么?
回答
这是类型推断的罕见失败。显式传递正确的显式类型有效:
views.push(Rc::<ListView>::clone(&list_view))
问题是根据预期类型(即)而不是参数类型Rc::clone(&list_view)推断Tin 。另一方面,当您调用它时,它使用了on 类型的实现,因此它解析为。Rc<T>Rc<dyn View>list_view.clone()Clonelist_viewRc::<ListView>::clone
如果上面的问题在你的代码中经常出现,并且你想在正常克隆和引用的浅克隆之间保持视觉上的区别,你可以写一个小助手特征:
trait RcClone : Clone {
fn rc_clone(&self) -> Self {
self.clone()
}
}
impl<T: ?Sized> RcClone for Rc<T> { }
impl<T: ?Sized> RcClone for Arc<T> { }
然后,您可以编写list_view.rc_clone()仅适用于引用计数类型的代码库。这仍然表明语义与常规克隆不同,同时没有类型推断问题。