簡體   English   中英

創建宏以簡化深層嵌套枚舉的聲明?

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

我想使用深度嵌套的枚舉來表示我游戲中的塊:

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 }

我發現聲明一個Element非常冗長:

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

是否可以創建一個宏來為我的枚舉聲明添加語法糖?

我希望創建一個可以自動解析枚舉路徑的宏,例如

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

使用 cdhowie 的From想法,我認為您只需要來自最低級別枚舉的特征暗示。 您可以跳過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