rust - 为通用特征实现特征

标签 rust

在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/

相关文章:

json - 如何将所有字段都是默认值的类型反序列化为 None ?

c - Rust ffi + wasm (yew -> cargo 网络启动) -> fatal error : 'math.h' file not found

multithreading - 从另一个线程调用 FnMut 回调

rust - 获取给定 LHS 和 RHS 类型的 Add 实现的关联输出类型

rust - 反复将变量传递给函数(改变所述变量)

rust - 如何计算两个 Rust 数组/切片/向量的点积?

rust - 如何返回对 optional 结构字段内值的引用?

rust - 错误: unable to infer enough type information about `_` ; type annotations required

rust - 用 Rust 读取文件 - 借用的值只存在到这里

rust - 是否可以使一种类型只能移动而不能复制?