I use serde/toml to read my Config
struct from a file.
However, one of the fields is a regular expression, which I want to be of type Regex
from the crate regex.
The problem is, that this crate has no serde support. So this does not work because of the regex
field:
use regex::Regex;
#[derive(serde::Deserialize)]
struct Config {
some_configuartion: bool,
regex: Regex, // this field is the problem
more_configuration: String,
}
However, Regex
implements TryFrom<String>
and FromStr
. So what I would like to have is that serde deserializes to String
and then uses a trait to convert it to Regex
. I expected that this works:
use regex::Regex;
#[derive(serde::Deserialize)]
struct Config {
some_configuartion: bool,
#[serde(try_from = "String")] // doesn't work
regex: Regex,
more_configuration: String,
}
Unfortunately, it doesn't work, because try_from
is not a field attribute, but just a container attribute. There is a field attribute called deserialize_with
which allows you to specify a specific deserialization function, but then I would need to write it myself. (That would be boilerplate, and I expect that somebody has done it already.)
What is the best solution to this?
I appreciate any help!