简体   繁体   中英

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.

#[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. Is custom-implementing Deserialize the cleanest method?

The Serde website has an entire example on how to serialize an enum as a number :

 [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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM