serde::ser

Trait SerializeStructVariant

Source
pub trait SerializeStructVariant {
    type Ok;
    type Error: Error;

    // Required methods
    fn serialize_field<T>(
        &mut self,
        key: &'static str,
        value: &T,
    ) -> Result<(), Self::Error>
       where T: Serialize + ?Sized;
    fn end(self) -> Result<Self::Ok, Self::Error>;

    // Provided method
    fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { ... }
}
Expand description

Returned from Serializer::serialize_struct_variant.

§Example use

use serde::ser::{Serialize, SerializeStructVariant, Serializer};

enum E {
    S { r: u8, g: u8, b: u8 },
}

impl Serialize for E {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            E::S {
                ref r,
                ref g,
                ref b,
            } => {
                let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?;
                sv.serialize_field("r", r)?;
                sv.serialize_field("g", g)?;
                sv.serialize_field("b", b)?;
                sv.end()
            }
        }
    }
}

§Example implementation

The example data format presented on the website demonstrates an implementation of SerializeStructVariant for a basic JSON data format.

Required Associated Types§

Source

type Ok

Must match the Ok type of our Serializer.

Source

type Error: Error

Must match the Error type of our Serializer.

Required Methods§

Source

fn serialize_field<T>( &mut self, key: &'static str, value: &T, ) -> Result<(), Self::Error>
where T: Serialize + ?Sized,

Serialize a struct variant field.

Source

fn end(self) -> Result<Self::Ok, Self::Error>

Finish serializing a struct variant.

Provided Methods§

Source

fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error>

Indicate that a struct variant field has been skipped.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§