是否可以从一个结构声明列表中声明一个枚举,并将它们作为其变体来包含?
就像这样(未包装):
struct CommandA {
// --snip--
}
struct CommandB {
// --snip--
}
enum Commands {
CommandA(CommandA),
CommandB(CommandB),
}
我的目标是使用structs来声明串行协议的命令,而不必声明重复的类型(我已经计算出的其他类型)。
我想做这样的事情:
#[derive(Command)]
#[repr(C, packed(1))]
struct CommandA {
// --snip--
}
#[derive(Command)]
#[repr(C, packed(1))]
struct CommandB {
// --snip--
}
或者有macro_rules的东西也会很棒。
不使用trait Command {}
的原因是因为协议“用户”中的一个将是no_std
(一个微控制器),所以我不能使用Box<dyn Command>
,而枚举作为该类型的“所有捕获”容器。
发布于 2022-08-18 06:32:50
您可以使用宏来模拟这种行为。缺点是,这需要在一个地方实现所有的结构。
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),*
})*
};
}
使用示例:
enum_of_structs! {
#[derive(Debug)]
enum Command {
#[derive(Debug)]
#[derive(Clone)]
pub CommandA {
pub field1: u32,
field2: String,
},
#[derive(Debug)]
CommandB {
field2: usize,
}
}
}
见游乐场。
https://stackoverflow.com/questions/73404638
复制相似问题