gpt4 book ai didi

rust - 如何在转换为 trait 对象时使用 Rc::clone?

转载 作者:行者123 更新时间:2023-12-04 12:04:40 27 4
gpt4 key购买 nike

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的类型是什么?可以直接调用吗?
写这个的惯用方式是什么?

最佳答案

这是类型推断的罕见失败。显式传递正确的显式类型有效:

views.push(Rc::<ListView>::clone(&list_view))
问题是 Rc::clone(&list_view)推断 TRc<T>基于预期类型(即 Rc<dyn View> ),而不是参数类型。另一方面,当您拨打 list_view.clone() 时它使用 Clone 的实现关于 list_view 的类型因此它解析为 Rc::<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()在您的代码库中,它仅适用于 refcounted 类型。这仍然表明语义与常规克隆不同,同时没有类型推断问题。

关于rust - 如何在转换为 trait 对象时使用 Rc::clone?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68342546/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com