How to deserialize enum


#1
#[derive(Clone, Copy, PartialEq, Eq, Debug, Deserialize)]
pub enum EnumType {
    A,
    B,
    C,
}
#[derive(Clone, PartialEq, Eq, Debug, Deserialize)]
pub struct MyConfig {
    pub a: Option<String>,
    pub b: EnumType,
}

config.yml is

a: ...
b: A

When run this app. the error message is

Can't deserialize config invalid type: string "A", expected enum EnumType

What is problem?
Thanks in advance.


#2

It seems to work when I tried it:

use serde::Deserialize;

#[derive(Deserialize, Debug)]
enum EnumType {
    A,
    B,
    C,
}

#[derive(Deserialize, Debug)]
struct MyConfig {
    a: Option<String>,
    b: EnumType,
}

fn main() {
    let config_yml = "a: ...\nb: A\n";

    println!("{:?}", serde_yaml::from_str::<MyConfig>(config_yml).unwrap());
}

#3

I am deserialize it using this.

 let mut config: MyConfig = serde_ignored::deserialize(settings, |path| {
        unused.insert(path.to_string());
    })

#4

That also works when I tried it.

use serde::Deserialize;
use serde_yaml::Value;
use std::collections::BTreeSet;

#[derive(Deserialize, Debug)]
enum EnumType {
    A,
    B,
    C,
}

#[derive(Deserialize, Debug)]
struct MyConfig {
    a: Option<String>,
    b: EnumType,
}

fn main() {
    let config_yml = "a: ...\nb: A\n";
    let settings: Value = serde_yaml::from_str(config_yml).unwrap();

    let mut unused = BTreeSet::new();
    let config: MyConfig = serde_ignored::deserialize(settings, |path| {
        unused.insert(path.to_string());
    }).unwrap();

    println!("{:?}", config);
}

#5

Thanks for your kindness.

Actually.
enum is declared wrapped by arg_enum!
Does it make problem?

arg_enum! {
   #[derive(Deserialize, Debug)]
   enum EnumType {
       A,
       B,
       C,
   }
}

#6

That also works when I tried it.

#[macro_use]
extern crate clap;

use serde::Deserialize;
use serde_yaml::Value;
use std::collections::BTreeSet;

arg_enum! {
    #[derive(Deserialize, Debug)]
    enum EnumType {
        A,
        B,
        C,
    }
}

#[derive(Deserialize, Debug)]
struct MyConfig {
    a: Option<String>,
    b: EnumType,
}

fn main() {
    let config_yml = "a: ...\nb: A\n";
    let settings: Value = serde_yaml::from_str(config_yml).unwrap();

    let mut unused = BTreeSet::new();
    let config: MyConfig = serde_ignored::deserialize(settings, |path| {
        unused.insert(path.to_string());
    }).unwrap();

    println!("{:?}", config);
}

#7

At this point it may be good to stop and have you put together a Minimal, Complete, and Verifiable example: https://stackoverflow.com/help/mcve.