首页 > 解决方案 > 如何接受扩展 PartialEq 的盒装特征对象?

问题描述

我想创建一个自定义类型,它接受任何实现扩展特征的对象PartialEq

操场

// In the external crate

// Actual Type:-
// [webdriver::command::ExtensionCommand](https://docs.rs/webdriver/0.40.2/webdriver/command/enum.WebDriverExtensionCommand.html)
pub trait Foo: Send + Clone + PartialEq {}

// Actual Type:-
// [webdriver::command::WebDriverCommand](https://docs.rs/webdriver/0.40.2/webdriver/command/enum.WebDriverCommand.html)
pub struct Bar<T: Foo> {
    foo: T,
}

// In my crate
type BarTwo = Bar<Box<dyn Foo>>;

我无法更改特征或结构,因为这些类型不在我的箱子中。我不能将泛型类型用于BarTwo.

输出

error[E0038]: the trait `Foo` cannot be made into an object
  --> src/lib.rs:12:23
   |
4  | pub trait Foo : Send + Clone + PartialEq{}
   |           ---                  --------- ...because it uses `Self` as a type parameter in this
   |           |
   |           this trait cannot be made into an object...
...
12 | type BarTwo = Bar<Box<dyn Foo>>;
   |                       ^^^^^^^ the trait `Foo` cannot be made into an object

标签: structrusttraits

解决方案


推荐阅读