types - 如何在不执行功能的情况下强制执行 super 特征?

标签 types rust

我希望能够说“此特征是该 super 特征的一个子代,因此它应该实现其所有功能”。
问题是trait X: Y {}意味着必须实现YX。我只希望实现X,但要确保所有功能都与Y匹配。
Playground link

trait GeneralA {
    fn get_x() -> String;
}

// Issue: cannot do `SpecificA : GeneralA` without also implementing GeneralA, but I want to enforce only having specific implementations, no general or default functions are possible.
trait SpecificA {
    fn get_x() -> String;
}

trait SpecificB {
    fn get_x() -> String;
}

struct S1;

impl SpecificA for S1 {
    fn get_x() -> String {
        "SpecificA->get_x".to_string()
    }
}

impl SpecificB for S1 {
    fn get_x() -> String {
        "SpecificB->get_x".to_string()
    }
}

fn main() {
    dbg!(<S1 as SpecificA>::get_x());
    dbg!(<S1 as SpecificB>::get_x());
}
我要在类型系统中描述的内容:
  • 结构可以实现零个或多个SpecificX特征。
  • 结构无法实现GeneralA特性。
  • 所有SpecificX特性应具有GeneralA特性的所有功能。
  • 强制转换为特征类型时,如果未针对该结构实现编译器,则编译器应出错。

  • 问题是Rust希望我实现GeneralASpecificX
    如何在类型系统中执行此操作?

    最佳答案

    如果未实现特征的“通用”版本,而未实现“特定”版本,则它们之间的关系不能成为超特征关系。听起来您想要的是通用特征,以及一些用于对其进行参数化的标记类型。

    trait HasX<T> {
        fn get_x() -> String;
    }
    
    struct A {}
    
    impl HasX<A> for S1 {
        fn get_x() -> String {
            "SpecificA->get_x".to_string()
        }
    }
    
    struct B {}
    
    impl HasX<B> for S1 {
        fn get_x() -> String {
            "SpecificB->get_x".to_string()
        }
    }
    
    无需实例化AB¹–它们仅存在于参数化HasX的情况下。 (根据问题的性质,可能已经有一些类型可用于参数化HasX;在这种情况下,您无需创建新的类型。)

    ¹可以使用空的struct(例如enum)代替空的enum A {}来强制执行永不实例化的方法,尽管这样做会牺牲它们为您提供的一些灵活性。

    关于types - 如何在不执行功能的情况下强制执行 super 特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64406203/

    相关文章:

    rust - 我可以在不使用泛型类型的情况下获得多特征实例的特征对象吗?

    Rust(新手): Read and write (mutable) access to the same underlying array from multiple threads for in-memory database?

    rust - 如何匹配 Rust 中的结构字段?

    rust - Rust 中的命令模式

    python - 如何检查可迭代对象是否允许多次通过?

    javascript - 我可以使用 constructor.name 来检测 JavaScript 中的类型吗

    python - 如何绕过违反直觉的 numpy 行为

    typescript - 如何指定 TypeScript 匿名内联箭头函数的返回类型

    generics - 为什么 Send on trait implementations 的 trait bounds 被忽略?

    Haskell 函数采用可变参数函数作为参数(并返回除该函数之外的其他内容),无需灵活实例,纯 Haskell2010