I'm trying to implement Serialize for an enum that includes struct variants. The serde.rs documentation indicates the following:
enum E { // Use three-step process: // 1. serialize_struct_variant // 2. serialize_field // 3. end Color { r: u8, g: u8, b: u8 }, // Use three-step process: // 1. serialize_tuple_variant // 2. serialize_field // 3. end Point2D(f64, f64), // Use serialize_newtype_variant. Inches(u64), // Use serialize_unit_variant. Instance, } With that in mind, I proceeded to implemention:
use serde::ser::{Serialize, SerializeStructVariant, Serializer}; use serde_derive::Deserialize; #[derive(Deserialize)] enum Variants { VariantA, VariantB { k: u32, p: f64 }, } impl Serialize for Variants { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { match *self { Variants::VariantA => serializer.serialize_unit_variant("Variants", 0, "VariantA"), Variants::VariantB { ref k, ref p } => { let mut state = serializer.serialize_struct_variant("Variants", 1, "VariantB", 2)?; state.serialize_field("k", k)?; state.serialize_field("p", p)?; state.end() } } } } fn main() { let x = Variants::VariantB { k: 5, p: 5.0 }; let toml_str = toml::to_string(&x).unwrap(); println!("{}", toml_str); } The code compiles, but when I run it it fails:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: UnsupportedType', src/libcore/result.rs:999:5 note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace. I figured the issue must be in my use of the API, so I consulted the API documentation for StructVariant and it looks practically the same as my code. I'm sure I'm missing something, but I don't see it based on the docs and output.
Serializelike most usages?