How to deserialize enum

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

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());
}

I am deserialize it using this.

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

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);
}

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,
   }
}

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);
}

At this point it may be good to stop and have you put together a Minimal, Complete, and Verifiable example: How to create a Minimal, Reproducible Example - Help Center - Stack Overflow.

1 Like