serde icon indicating copy to clipboard operation
serde copied to clipboard

Add `from`, `try_from`, `from_str`, ... as field attributes

Open jbirnick opened this issue 10 months ago • 0 comments

Many crates have From<String> or From<usize> or FromStr implementations on their structs, but don't have support for serde. To use them with serde we would need the from, try_from, and similar attributes also on fields (not just on containers).

For example, I want to read a regular expression from a TOML config file. Regex (from the crate regex) does implement From<String> (and similar) but doesn't have serde support. I would like to do the following:

use regex::Regex;

#[derive(serde::Deserialize)]
struct Config {
    some_configuartion: bool,
    #[serde(try_from = "String")]
    regex: Regex,
    more_configuration: String,
}

As this is already a container attribute (just not a field attribute), I think it wouldn't be too much work to implement, am I wrong?

It definitely would be great to have this feature. Many people are looking for it, see for example this pull request.

jbirnick avatar Sep 05 '23 14:09 jbirnick