在Rust中,如何实现通用特征的特质?
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))
}
}
最佳答案
不可能是这样,原因是它会模棱两可。
考虑这样的情况:
struct A;
impl One<u16> for A {}
impl One<u32> for A {}
One
将基于两个Two
实现中的哪一个?两者都满足毯式Two
实现的前提条件,但是Two
对于任何类型只能实现一次。就像您要提供两个单独的impl Two for A
块一样。在问题澄清后进行编辑:
上面的内容仍然成立,但是您可能想尝试是否可以将Select变成类型,方法可能是将其变成围绕selectable的包装。
关于rust - 为通用特征实现特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65622443/