2

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

我想要的是如下内容:

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是意外类型,在这种情况下它应该返回错误。

但是 Rust 不会让我Option<&SomeType>MyClonable.

4

1 回答 1

0

你不能。trait 对象只允许您访问 trait 方法。您需要手动指定要向下转换的具体类型,如本 QA 中所述:如何从 trait 对象中获取对具体类型的引用?.

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

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

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) { }
}
于 2020-01-15T02:48:08.827 回答