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 for more ergonomic defaults #1006

Closed
skorokithakis opened this issue Jul 27, 2017 · 1 comment
Closed

Allow for more ergonomic defaults #1006

skorokithakis opened this issue Jul 27, 2017 · 1 comment

Comments

@skorokithakis
Copy link

skorokithakis commented Jul 27, 2017

I'm sorry in advance if this is a bad suggestion, I'm new to Rust. However, I find myself having a problem where I need to deserialize some settings and I need sane defaults for some of the fields, and serde does not provide a good way for me to do that.

I have a struct that looks like this:

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Config {
    hostname: String,
    smtp_port: u16,
    pop3_port: u16,
    available: bool,
}

I would like to make the ports and available optional, but I would like hostname (and other fields not shown here) to be mandatory. However, there is no good way to tell serde to use defaults for these fields, short of littering my code with one function for each field and telling serde to call that.

It would help a lot if I could just say something like #[serde(default=110)] and have serde assign that value if that field were missing from the JSON file.

@dtolnay
Copy link
Member

dtolnay commented Jul 28, 2017

Thanks! We are already tracking this in #368.

The challenge is that if default=110 means assign 110 as the default value, then one would assume default="x" means assign "x" as the default value. Instead it means assign x().

Let us know in the other issue if you have a preference for how to solve this.

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