如何将特征转换为具体类型?

How to convert trait to concrete type?

我有一个 trait 对象,我想知道它指向的具体对象,但我不知道如何获取具体对象。

我想要的是类似下面的东西:

trait MyClonable {
   /** copy from another MyClonable */
   fn my_clone_from(&mut self, other: &Self)->Result<(), MyError>;
}

impl MyClonable for SomeType {
   fn my_clone_from(&mut self, other: &MyClonable)->Result<(), MyError> {...}
}

所以我可以这样说:

let mut new_thing = SomeType::new();
new_thing.my_clone_from(&old_thing)?;

然后 new_thing 将包含 old_thing 的某种副本,除非 old_thing 是意外类型,在这种情况下它应该 return错误。

但是 Rust 不会让我从 MyClonable.

得到类似 Option<&SomeType> 的东西

你不能。特征对象只允许您访问特征方法。您需要手动指定要向下转换的具体类型,如本 QA 中所述:.

然后,您可以尝试向下转换为每个已知类型,直到其中一个成功,但那是脏的。

相反,使用泛型会更合适:

trait MyClonable<T> {
    fn my_clone_from(&mut self, other: &T);
}

现在您可以为所有支持的类型实现此特征:

impl MyClonable<u32> for i32 {
    fn my_clone_from(&mut self, _other: &u32) { }
}

impl MyClonable<Tomato> for i32 {
    fn my_clone_from(&mut self, _other: &Tomato) { }
}