【发布时间】:2018-02-14 08:53:12
【问题描述】:
所以我正在制作一个基于simplecs的ECS。
我有一个宏,可以生成如下所示的实体结构:
($($name:ident : $component:ty,)*) => {
/// A collection of pointers to components
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Entity {
$(
pub $name: Option<($component)>,
)*
children: Vec<Entity>
}
}
我的目标是使用 serde 来序列化实体,但这会在组件应该存在的地方留下一堆丑陋的 None 值。所以我尝试实现一个如下所示的自定义序列化程序:
impl Serialize for Entity {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let mut num_fields = 0;
$(
match self.$name {
Some => num_fields += 1,
None => {}
};
)*
let mut state = serializer.serialize_struct("Entity", num_fields)?;
// do serialize
state.end()
}
}
序列化程序尝试通过作为宏参数 ($name) 提供的名称访问字段,但是当我去编译它时,我得到了这个错误
error[E0530]: match bindings cannot shadow tuple variants
|
| Some => {}
| ^^^^ cannot be named the same as a tuple variant
【问题讨论】:
-
您使用的是
Some而不是Some(pattern)。如果您不关心内容,请在 if 条件中使用self.$name.is_some()而不是使用匹配项。