为本地泛型类型实现外来特征

时间:2019-10-16 15:50:30

标签: rust

我正在尝试使用静态分派从板条箱B实现一个特征。我包装了外国特征,但是在impl<T>行中遇到了问题:

extern crate a;
extern crate b;

pub trait C: a::A {}

impl<T: C> b::B for T {}

我要寻找的最终结果是使用静态分派为特征b::B的实现者实现C

我遇到以下错误:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
 --> c/src/lib.rs:3:1
  |
3 | impl<T: C> b::B for T {}
  | ^^^^^^^^^^^^^^^^^^^^^ type parameter `T` must be used as the type parameter for some local type
  |
  = note: only traits defined in the current crate can be implemented for a type parameter

我可以通过使用动态调度-impl b::B for dyn C来解决此问题,但希望通过静态调度来实现。

我已经尝试过:

1 个答案:

答案 0 :(得分:1)

我通常要做的是将外来类型包装在struct中(而不是引入派生自外来类型的新trait):

extern crate a;
extern crate b;

pub struct C<T: a::A> {
    pub t: T,
}

impl<T: a::A> b::B for C<T> {}

但是,有时这需要一些样板才能在C和“正常”类型之间转换。

有时称为“ NewType模式”(如https://github.com/Ixrec/rust-orphan-rules)。