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

#[serde(skip_deserializing)] for Option<T> wrongly requires T to implement Default #2759

Open
SylvainGarrigues opened this issue Jun 19, 2024 · 4 comments

Comments

@SylvainGarrigues
Copy link

Quoting the documentation for #[serde(skip_deserializing)]:
When deserializing, Serde will use Default::default() or the function given by default = "..." to get a default value for this field.

Option<T> defaults to None event if T doesn't implement Default, so why does the compiler complain T must implement such Default trait for me to be able to derive Deserialize?

Sample code (uncomment /* Default */ to have the code compile):

use serde::Deserialize;
use std::fmt::Debug;

#[derive(Debug /*, Default*/)]
struct Hidden(());

#[derive(Deserialize)]
struct Config<T> {
    ip: String,
    #[serde(skip_deserializing)]
    hidden: Option<T>,
}

fn load_config<T /*: Default*/>(s: &str) -> Config<T> {
    toml::from_str(s).unwrap()
}

fn main() {
    let config: Config<Hidden> = load_config(r#"ip = '127.0.0.1'"#);
    println!("ip={:?}, hidden={:?}", config.ip, config.hidden);
}

Same code in Rust playground

@SylvainGarrigues
Copy link
Author

Oddly enough, I noticed that in my case, manually specifying the default function to Default::default() makes the code compile without restraining T to implement Default:

#[serde(skip_deserializing, default = "Default::default")]

@Mingun
Copy link
Contributor

Mingun commented Jun 19, 2024

This is because serde_derive constraints generic types of the struct (T) to required traits instead of actual types of fields (Option<T>).

@avkonst
Copy link

avkonst commented Jul 28, 2024

And perhaps this ^ is a bug? I faced the same problem with serde(default) attribute for a field of custom generic type, which implements Default.
image

@avkonst
Copy link

avkonst commented Jul 28, 2024

Using the explicit path does not help either:
image

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

No branches or pull requests

3 participants