简体   繁体   English

如何配置 Serde 以使用枚举变体的判别式而不是名称?

[英]How do I configure Serde to use an enum variant's discriminant rather than name?

I'm parsing an INI-style file that uses integers for enumerators.我正在解析一个使用整数作为枚举器的 INI 样式文件。

#[derive(Debug, Deserialize, Serialize)]
pub enum MyThing {
    First = 0,
    Second = 1,
    Third = 2,
}

In the file, the value will get serialized like so:在文件中,值将像这样被序列化:

thing=0

However, Serde by default matches against the variant name rather than the discriminant.但是,默认情况下,Serde 匹配变体名称而不是判别式。 Is custom-implementing Deserialize the cleanest method?自定义实现Deserialize是最干净的方法吗?

The Serde website has an entire example on how to serialize an enum as a number : Serde 网站有一个关于如何将枚举序列化为数字完整示例

 [dependencies] serde = "1.0" serde_repr = "0.1"
 use serde_repr::*; #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] #[repr(u8)] enum SmallPrime { Two = 2, Three = 3, Five = 5, Seven = 7, } fn main() { use SmallPrime::*; let nums = vec![Two, Three, Five, Seven]; // Prints [2,3,5,7] println!("{}", serde_json::to_string(&nums).unwrap()); assert_eq!(Two, serde_json::from_str("2").unwrap()); }

I would believe that this is the best way to do it as it's recommended by the crate authors themselves.我相信这是最好的方法,因为它是由板条箱作者自己推荐的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 serde 反序列化为特定的枚举变体? - How do I use serde to deserialize into a specific enum variant? 如何仅序列化变量的名称并忽略结构中枚举字段的值(serde) - How to serialise only name of variant and ignore value for enum field in struct (serde) 如何对枚举进行变异,然后返回对枚举变体的引用? - How do I mutate an enum and then return a reference to an enum variant? 如何在 RUST 中将枚举变量的名称转换为字符串? - How to convert the name of a enum's variant to a String in RUST? 如何使用字符串而不是顺序值对枚举属性执行where查询? - How do I perform a where query on an enum attribute with a string rather than the ordinal value? 如何传递枚举变量以匹配作为函数参数? - How do I pass an enum variant to match on as a function parameter? 如何有条件地检查枚举是一种变体还是另一种变体? - How do I conditionally check if an enum is one variant or another? 如何在忽略判别式的情况下找到枚举的大小? - How can I find the size of an enum while ignoring the discriminant? 如何根据键名反序列化为枚举变体? - How to deserialize into a enum variant based on a key name? 如何区分枚举索引项的枚举名称? - How do I differentiate between an enum's name from enum index items?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM