如何解决由于泛型类型参数,无法将特征设为对象
在我的代码中,我有一些实现Trait1的对象。我还具有实现Trait2的各种对象,该对象期望将Trait1对象作为参数。当我尝试创建满足Trait2的对象矢量时,出现编译器错误。
我可以得到的最简单的复制方式:
trait Trait1 {
fn doit(&self);
}
trait Trait2 {
fn do_other_thing(&self,obj: &impl Trait1);
}
fn main() {
let mut myvec = Vec::<Box<dyn Trait2>>::new();
}
这会导致编译器错误:
error[E0038]: the trait `Trait2` cannot be made into an object
--> src/main.rs:10:18
|
5 | trait Trait2 {
| ------ this trait cannot be made into an object...
6 | fn do_other_thing(&self,obj: &impl Trait1);
| -------------- ...because method `do_other_thing` has generic type parameters
...
10 | let mut myvec = Vec::<Box<dyn Trait2>>::new();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Trait2` cannot be made into an object
|
= help: consider moving `do_other_thing` to another trait
有什么办法可以实现这样的目标吗? “ myvec”必须在Trait2上具有动态性,因为我希望持有实现此特征的不同类型。有什么方法可以允许'obj'在Trait1上完全通用,还是我必须将其绑定到实现Trait1的特定类型?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。