[英]Generic type for types implementing trait or dereferencing to trait
[英]Implementing a foreign trait for a local generic type
我正在尝试使用 static 调度实现来自板条箱 A 的特征,以获得来自板条箱 B 的特征。 我正在包装外国特征,但impl<T>
行有问题:
extern crate a;
extern crate b;
pub trait C: a::A {}
impl<T: C> b::B for T {}
我正在寻找的最终结果是使用 static 调度为特征C
的实现者实现b::B
。
我收到以下错误:
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
- 但想通过 static 调度来实现这一点。
我已经尝试过:
Vec
实现特征,而是我自己的类型我通常做的是将外来类型包装在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中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.