【问题标题】:Type alias for enum枚举类型别名
【发布时间】:2015-11-08 23:12:29
【问题描述】:

有没有办法让下面的代码工作?也就是说,以类型别名导出枚举,并允许以新名称访问变体?

enum One { A, B, C }

type Two = One;

fn main() {
    // error: no associated item named `B` found for type `One` in the current scope
    let b = Two::B;
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    我认为类型别名不允许做你想做的事,但你可以在 use 语句中重命名枚举类型:

    enum One { A, B, C }
    
    fn main() {
        use One as Two;
        let b = Two::B;
    }
    

    您可以将其与 pub use 结合使用,以重新导出不同标识符下的类型:

    mod foo {
        pub enum One { A, B, C }
    }
    
    mod bar {
        pub use foo::One as Two;
    }
    
    fn main() {
        use bar::Two;
        let b = Two::B;
    }
    

    【讨论】:

    • 重新导出可以解决问题 - 我想枚举类型的行为更像是迷你模块而不是结构和原语是有意义的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2015-11-16
    • 2010-12-09
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2021-10-24
    相关资源
    最近更新 更多