首页 > 解决方案 > 为通用特征实现特征

问题描述

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

标签: rust

解决方案


不可能,原因是它会模棱两可。

想想这样的情况:

struct A;

impl One<u16> for A {}

impl One<u32> for A {}

这两个One实现中的哪一个Two将基于?两者都满足一揽子Two实现的先决条件,但Two对于任何类型都只能实现一次。就像您要提供两个单独的impl Two for A块一样。


问题澄清后编辑:

以上仍然成立,但您可能想尝试是否可以将 Select 变成一个类型,可能通过将它变成一个可选择的包装器。


推荐阅读