Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow flattened untagged Options in struct fields #1255

Closed
alberdingk-thijm opened this issue May 11, 2018 · 1 comment
Closed

Allow flattened untagged Options in struct fields #1255

alberdingk-thijm opened this issue May 11, 2018 · 1 comment

Comments

@alberdingk-thijm
Copy link

I have a small use case for #[serde(flatten)] that did not work as I expected due to the intermediary presence of an Option type. Here's what I mean:

#[derive(Serialize, Deserialize)]
enum Quux {
    A,
    B,
    C,
}

#[derive(Serialize, Deserialize)]
struct Bar {
    quux: Quux,
}

#[derive(Serialize, Deserialize)]
struct Foo {
    baz: i32,
    #[serde(flatten)]
    bar: Option<Bar>,
}

fn main() {
    let f : Foo = serde_json::from_str(r#"{
        "baz": 10,
        "quux": "A"
    }"#).unwrap();  // panics unwrapping 'Error("can only flatten structs and maps", line: 4, column: 5)'
}

I'm able to get around this problem by using my own untagged Option type.

#[derive(Serialize, Deserialize)]
enum Quux {
    A,
    B,
    C,
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum OptBar {
    Some(Bar),
    None,
}

#[derive(Serialize, Deserialize)]
struct Bar {
    quux: Quux,
}

#[derive(Serialize, Deserialize)]
struct Foo {
    baz: i32,
    #[serde(flatten)]
    bar: OptBar,
}

fn main() {
    let f : Foo = serde_json::from_str(r#"{
        "n": 10,
        "quux": "A"
    }"#).unwrap();  // returns a 'Foo { n: 10, bar: Some(Bar { quux: A }) }'
}

Is there any way to get around this otherwise? Continuing to use the standard Option type allows some more straightforward checking of Foo.bar, which is quite useful. Worst case scenario I can change my data representation.

@dtolnay
Copy link
Member

dtolnay commented May 12, 2018

Thanks, I released Serde 1.0.54 with a fix. Your code should work as written.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants