Can traits be used on enum types?

本秂侑毒 提交于 2019-11-28 03:50:02

问题


I read through the trait documentation and found a neat definition for using traits on structs. Is it possible to use traits on enum types? I have seen answers that say no, but they are 3 years old and don't quite do what I'm trying to do.

I tried to do this:

#[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`

I don't understand this error because the enum it references is in the same file. If I really can't use traits on enum variants, is there any way I can guarantee any enum trait must implement certain methods?


回答1:


Can traits be used on enum types?

Yes. In fact, you already have multiple traits defined for your enum; the traits Debug, Copy and Clone:

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

The problem is that you aren't attempting to implement Playable for your enum, you are trying to implement it for one of the enum's variants. Enum variants are not types.

As the error message tells you:

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

See also:

  • Can struct-like enums be used as types?
  • Is there a way to use existing structs as enum variants?


来源:https://stackoverflow.com/questions/51567350/can-traits-be-used-on-enum-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!