简体   繁体   English

创建宏以简化深层嵌套枚举的声明?

[英]Create macro to simplify declaration of deeply nested enum?

I want to use deeply nested enums to represent blocks in my game:我想使用深度嵌套的枚举来表示我游戏中的块:

enum Element { Void, Materal(Material) }
enum Material { Gas(Gas), NonGas(NonGas) }
enum NonGas { Liquid(Liquid), Solid(Solid) }
enum Solid { MovableSolid(MovableSolid), ImmovableSolid(ImmovableSolid) }
enum Gas { Smoke }
enum Liquid { Water }
enum ImmovableSolid { Bedrock }
enum MovableSolid { Sand, GunPowder }

I found it very verbose to declare an Element :我发现声明一个Element非常冗长:

let block: Element = Element::Materal(Material::NonGas(NonGas::Solid(Solid::ImmovableSolid(ImmovableSolid::Bedrock))));

Is it possible to create a macro to add syntactic sugar for my enum declaration?是否可以创建一个宏来为我的枚举声明添加语法糖?

I'm hoping to create a macro that can automagically resolve the enum path, for example我希望创建一个可以自动解析枚举路径的宏,例如

let block: Element = NewElement!(ImmovableSolid::Bedrock);

Using cdhowie's From idea, I think you'd only need trait impls from your lowest level enums.使用 cdhowie 的From想法,我认为您只需要来自最低级别枚举的特征暗示。 You can skip ones like impl From<Material> for Element because you need a child to create a Material , so it doesn't really make sense to start at that level.您可以跳过impl From<Material> for Element之类的,因为您需要一个子项来创建Material ,因此从该级别开始实际上没有意义。

impl From<Gas> for Element {
    fn from(e: Gas) -> Element {
        Element::Materal(Material::Gas(e))
    }
}

impl From<Liquid> for Element {
    fn from(e: Liquid) -> Element {
        Element::Materal(Material::NonGas(NonGas::Liquid(e)))
    }
}

impl From<ImmovableSolid> for Element {
    fn from(e: ImmovableSolid) -> Element {
        Element::Materal(Material::NonGas(NonGas::Solid(Solid::ImmovableSolid(e))))
    }
}

impl From<MovableSolid> for Element {
    fn from(e: MovableSolid) -> Element {
        Element::Materal(Material::NonGas(NonGas::Solid(Solid::MovableSolid(e))))
    }
}

fn main() {
    println!("{:?}", Element::from(ImmovableSolid::Bedrock));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM