【发布时间】:2021-01-09 18:41:51
【问题描述】:
在 Rust 中,如何为泛型 trait 实现 Trait?
trait One<S> {}
trait Two {}
// fails because S isn't contrained
impl<S, T> Two for T where T: One<S> {}
为了澄清,我正在尝试提供 BitAnd 特征
对于通用 Select 特征。
struct Thing<S> {
field: S,
}
trait Select<S> {
fn select(&self, thing: &Thing<S>) -> bool;
}
struct SelectUnion<S> (Box<dyn Select<S>>, Box<dyn Select<S>>);
// fails because S isn't contrained
impl<S, T> std::ops::BitAnd for T where T: Select<S> {
type Output = SelectUnion<S>;
fn bitand(self, rhs: Self) -> Self::Output {
SelectUnion(Box::new(self), Box::new(rhs))
}
}
【问题讨论】:
-
你打算用这些特征做什么?如果您搜索该错误,则会有大量结果,但在这个问题中并没有太多问题。
-
我假设 chrysn' 的答案仍然遵循,但您是否尝试过向 S 添加约束?即
where S: MyTrait -
@loganfsmyth 我已经澄清了这是要实现的目标。
-
@sam 我试过了,但仍然失败。 trait
S需要出现在正在实现的 trait 或“实现它的事物”中。
标签: rust