How To declare a enum from a list of structs?

Viewed 47

Is it possible to declare a enum from a list of struct declarations and also contain them as their variants?

Like so (unwrapped):


struct CommandA {
    // --snip--
}

struct CommandB {
    // --snip--
}

enum Commands {
  CommandA(CommandA),
  CommandB(CommandB),
}

My goal is to use structs to declare commands for a serial protocol, and not have to declare repeated types (the rest I have figured out).

I would like to do something like this:


#[derive(Command)]
#[repr(C, packed(1))]
struct CommandA {
  // --snip--
}


#[derive(Command)]
#[repr(C, packed(1))]
struct CommandB {
  // --snip--
}

Or something with a macro_rules also would be great.

The reason for not using a trait Command {} is because one of the protocol 'users' will be no_std (a micro controller), so I cant use Box<dyn Command> and the enum acts as 'catch-all' container for the type.

1 Answers

You can mimic this behavior with macros. The downside is that this requires implementing all the structs in a single place.

macro_rules! enum_of_structs {
    ($(#[$($emeta:meta),*])*
    $evis:vis enum $name:ident { 
        $($(#[$($smeta:meta),*])*
        $svis:vis $strct:ident {
            $($fvis:vis $field:ident : $ty:ty),* $(,)? 
        }),* $(,)?
    }) => {
        $(#[$($emeta),*])*
        $evis enum $name {
            $($strct($strct)),*
        }
        $(
        $(#[$($smeta),*])*
        $svis struct $strct {
            $($fvis $field: $ty),*
        })*
    };
}

Example of usage:

enum_of_structs! {
    #[derive(Debug)]
    enum Command {
        #[derive(Debug)]
        #[derive(Clone)]
        pub CommandA {
            pub field1: u32,
            field2: String,
        },
        #[derive(Debug)]
        CommandB {
            field2: usize,
        }
    }
}

See the playground.

Related