Can traits be used on enum types?

2020-02-01 07:50发布

问题:

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?