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

Easier way to declare default values #1814

Closed
mainrs opened this issue May 17, 2020 · 1 comment
Closed

Easier way to declare default values #1814

mainrs opened this issue May 17, 2020 · 1 comment

Comments

@mainrs
Copy link

mainrs commented May 17, 2020

I have a struct with a lot of fields (~ 50-ish). The types are mostly a number, a string or a bool. Is there an easier way to declare the default values then using the default attribute? E.g.:

pub struct Config {
    #[serde(default = "default_some_field")]
    some_field: String, // default value is "edged"
}

fn default_some_field() -> String {
    "edged".into()
}

I expected the argument to be the default value, e.g. default = "edged" where the proc_macro tries to into() into the type of the field. Maybe the current behaviour could be encoded behind a field called default_fn or something.

P.S.: I am not actually sure if the above proposal is currently possible in syn.

Further examples:

pub struct Config {
    #[serde(default = "4")]
    int_field: i32,
    #[serde(default = "true")]
    bool_field: bool,
}

Would all work as expected as the values can properly be converted using into() or parse.

pub struct Config {
    #[serde(default = "seven")]
    int_field: i32,
}

Wouldn't work as seven can't be parsed correctly into a number.

@dtolnay
Copy link
Member

dtolnay commented Jul 5, 2020

Closing as a duplicate of #368.

@dtolnay dtolnay closed this as completed Jul 5, 2020
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

2 participants