本文介绍了如何配置Serde使用枚举变量的判别式而不是名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解析一个使用整数作为枚举数的INI样式文件.

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

但是,默认情况下,Serde与变体名称而不是判别式匹配.自定义实现Deserialize是最干净的方法吗?

However, Serde by default matches against the variant name rather than the discriminant. Is custom-implementing Deserialize the cleanest method?

推荐答案

Serde网站上有一个整个示例关于如何将枚举序列化为数字:

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.

这篇关于如何配置Serde使用枚举变量的判别式而不是名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:19