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

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 这样的,因为你需要一个 child 来创建一个 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));
}