可以在枚举类型上使用特征吗? [英] Can traits be used on enum types?
问题描述
我通读了 trait 文档 并找到了一个简洁的在结构上使用特征的定义.是否可以在 enum
类型上使用特征?我看到过否定的答案,但他们已经 3 岁了,并没有完全按照我的意愿去做.
我尝试这样做:
#[derive(Debug, Copy, Clone)]酒吧枚举场景类型{过场动画,游戏,菜单,暂停,学分,出口,}//我们要保证每个SceneType都可以静态播放特质可玩{fn 播放();}impl Playable for SceneType::Cutscene {fn 播放(){}}
错误[E0573]:预期类型,发现变体`SceneType::Cutscene`-->src/main.rs:16:19|16 |impl Playable for SceneType::Cutscene {|^^^^^^^^^^^^^^^^^^^|||不是类型|帮助:您可以尝试使用变体的枚举:`SceneType`
我不明白这个错误,因为它引用的枚举在同一个文件中.如果我真的不能在 enum 变体上使用 trait,有什么办法可以保证任何 enum trait 都必须实现某些方法吗?
可以在枚举类型上使用特征吗?
是的.事实上,您已经为枚举定义了多个特征;特征 Debug
, Copy
和 克隆
:
#[derive(Debug, Copy, Clone)]酒吧枚举场景类型
问题是您没有尝试为枚举实现 Playable
,而是尝试为枚举的 变体 之一实现它.枚举变体不是类型.
正如错误消息告诉您的:
<块引用>help:你可以尝试使用变体的枚举:`SceneType`
impl Playable for SceneType {fn 播放(){}}
另见:
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屋!