特征可以用于枚举类型吗? [英] Can traits be used on enum types?

查看:97
本文介绍了特征可以用于枚举类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通读了特征文档,发现整洁在结构上使用特征的定义。是否可以在枚举类型上使用特征?我已经看到回答说不的答案,但是他们已经3岁了,还没有完全按照我的意愿去做。



我试图这样做:

 #[派生(调试,复制,克隆)] 
pub enum SceneType {
过场动画,
游戏,
菜单,
暂停,
积分,
退出,
}

//我们要保证每个SceneType都可以静态地播放
特质Playable {
fn play();
}

impl可用于SceneType :: Cutscene {
fn play(){}
}



 错误[E0573]:预期类型,找到了变量`SceneType :: Cutscene` 
-> src / main.rs:16:19
|
16 | impl可用于SceneType :: Cutscene {
|
| ^^^^^^^^^^^^^^^^^^^^
| |
|不是
类型|帮助:您可以尝试使用变体的枚举:`SceneType`

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

解决方案

< blockquote>

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


。实际上,您已经为枚举定义了多个特征。特征 Debug 复制 克隆


 #[派生(调试,复制,克隆)] 
pub枚举SceneType


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



错误消息告诉您:


  help:您可以尝试使用变体的枚举:`SceneType` 




  impl可用于SceneType {
fn play(){}
}

另请参见:




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?

解决方案

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:

这篇关于特征可以用于枚举类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆