简体   繁体   English

为通用特征实现特征

[英]Implement a trait for a generic trait

In Rust, how to implement a Trait for a generic trait?在 Rust 中,如何为通用特征实现特征?

trait One<S> {}

trait Two {}

// fails because S isn't contrained
impl<S, T> Two for T where T: One<S> {}

To clarify, I'm trying to provide the BitAnd trait for a generic Select trait.为了澄清,我试图为通用Select特征提供BitAnd特征。

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))
    }
}

It can't be, and the reason is that it would be ambiguous.不可能,原因是它会模棱两可。

Think of a situation like this:想想这样的情况:

struct A;

impl One<u16> for A {}

impl One<u32> for A {}

Which of the two One implementations would the Two be based on? Two将基于两个One实现中的哪一个? Both satisfy the preconditions for the blanket Two implementation, but Two can only be implemented once for any type.两者都满足一揽子Two实现的先决条件,但Two对于任何类型都只能实现一次。 It's like as if you'd provide two separate impl Two for A blocks.就像您要impl Two for A一样。


edit after the question clarification:问题澄清后编辑:

The above still holds, but you may want to try whether you can make Select into a type, possibly by turning it into a wrapper around a selectable.以上仍然成立,但您可能想尝试是否可以将 Select 变成一种类型,可能通过将其变成围绕可选的包装器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM