【发布时间】:2021-07-12 06:00:54
【问题描述】:
Rust 书说使用 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 的类型是什么?可以直接调用吗?
写这个的惯用方式是什么?
【问题讨论】:
标签: rust trait-objects