-
-
Notifications
You must be signed in to change notification settings - Fork 779
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
"Inlining" enum into containing struct #761
Comments
We are tracking better support for this case in #119. For now there are two possible workarounds but neither one is great. You can deserialize as one of these and then immediately convert it to your better representation for the rest of your program to use. #[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Config {
Url {
name: String,
other_common_stuff: u64,
url: String,
}
Dummy {
name: String,
other_common_stuff: u64,
print: bool,
}
} or #[derive(Serialize, Deserialize)]
struct Config {
name: String,
other_common_stuff: u64,
#[serde(skip_serializing_if = "Option::is_none")]
url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
print: Option<bool>,
} Once we implement #119 it will look like this: #[derive(Serialize, Deserialize)]
struct Config {
name: String,
other_common_stuff: u64,
#[serde(flatten)]
mode: ConfigMode,
}
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum ConfigMode {
Url {
url: String,
}
Dummy {
print: bool,
}
} |
Thanks, that's exactly what I'm looking for! |
Working example https://play.rust-lang.org/?gist=6457ea3e0824e80c0f1270cacb052e57 Prints:
How to nicely remove
|
Technically, using Additionally, if the containing struct is tagged with Yes, |
I'm trying to (de)serialize a TOML config which basically allows the user to choose a mode. It essentially looks like this:
I want the config file to look somewhat like this:
Or, for selecting the
Dummy
mode:So I basically need to "inline" the
ConfigMode
into theConfig
struct for (de)serialization. Since serde supports untagged enums, this doesn't seem too hard to implement to me, right?The text was updated successfully, but these errors were encountered: