Skip to content
This repository was archived by the owner on Mar 25, 2024. It is now read-only.
This repository was archived by the owner on Mar 25, 2024. It is now read-only.

[Bug] Newtype enum variant deserialization failure when used with #[serde(flatten)] #344

@cyqsimon

Description

@cyqsimon

TL;DR

If you create an enum that contains a newtype variant, wrap the enum in a struct, wrap the said struct in another struct and use #[serde(flatten)] on it, the struct can no longer successfully deserialize (while serialization is unaffected).

Deserialization fails with message: untagged and internally tagged enums do not support enum input.


That's not a very helpful description so here's a MRE:

use serde::{Deserialize, Serialize};

fn main() {
    // this works
    let gender = Gender::Other("F22".into());
    assert_eq!(
        &gender,
        &serde_yaml::from_str(&dbg!(serde_yaml::to_string(&gender).unwrap())).unwrap()
    );

    // this still works
    let info = Info { gender };
    assert_eq!(
        &info,
        &serde_yaml::from_str(&dbg!(serde_yaml::to_string(&info).unwrap())).unwrap()
    );

    // this errors
    let user = User { info };
    assert_eq!(
        &user,
        &serde_yaml::from_str(&dbg!(serde_yaml::to_string(&user).unwrap())).unwrap()
    );
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
enum Gender {
    Female,
    Male,
    Other(String),
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
struct Info {
    gender: Gender,
}

#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
struct User {
    #[serde(flatten)]
    info: Info,
}

Misc

I tried the exact same example using serde_json, no errors. So I think this is a serde_yaml issue rather than a serde issue.

A quick search did find this issue though, not sure if it's related: ron-rs/ron#217.

Versions

  • OS: Linux 6.0.8 x86_64
  • rust: 1.65.0 (stable-x86_64-unknown-linux-gnu)
  • serde: 1.0.147
  • serde_yaml: 0.9.14

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions