【问题标题】:Can traits be used on enum types?特征可以用于枚举类型吗?
【发布时间】:2019-01-05 03:11:33
【问题描述】:

我通读了trait documentation 并找到了在结构上使用特征的简洁定义。是否可以在 enum 类型上使用特征?我看到回答说不,但他们已经 3 岁了,并没有完全按照我的意愿去做。

我尝试过这样做:

#[derive(Debug, Copy, Clone)]
pub enum SceneType {
    Cutscene,
    Game,
    Menu,
    Pause,
    Credits,
    Exit,
}

//We want to guarantee every SceneType can be played statically
trait Playable {
    fn play();
}

impl Playable for SceneType::Cutscene {
    fn play() {}
}
error[E0573]: expected type, found variant `SceneType::Cutscene`
  --> src/main.rs:16:19
   |
16 | impl Playable for SceneType::Cutscene {
   |                   ^^^^^^^^^^^^^^^^^^^
   |                   |
   |                   not a type
   |                   help: you can try using the variant's enum: `SceneType`

我不明白这个错误,因为它引用的枚举在同一个文件中。如果我真的不能在枚举变体上使用特征,有什么办法可以保证任何枚举特征都必须实现某些方法?

【问题讨论】:

    标签: enums rust traits


    【解决方案1】:

    特征可以用于枚举类型吗?

    是的。事实上,你已经为你的枚举定义了多个特征;特征DebugCopyClone

    #[derive(Debug, Copy, Clone)]
    pub enum SceneType
    

    问题是您没有尝试为您的枚举实现Playable,而是尝试为枚举的变体之一 实现它。枚举变体不是类型

    正如错误信息告诉你的那样:

    help: you can try using the variant's enum: `SceneType`
    
    impl Playable for SceneType {
        fn play() {}
    }
    

    另见:

    【讨论】:

    • 但是如果我想为所有枚举变体(Cutscene.play()、Game.play() 等)实现 Playable,我应该怎么做?在 SceneType.play() 方法中添加match 表达式?
    • @rusnasonov 是的。
    • 这种语言不是很奇怪,因为它允许不同数据类型的枚举。因此,不允许在 enum 上使用 trait 有点违反直觉。想法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    相关资源
    最近更新 更多