# serde 1.0.229

> Serde is a framework for ***ser***ializing and ***de***serializing Rust data

## serde

### serde › Serde

Serde is a framework for ***ser***ializing and ***de***serializing Rust data
structures efficiently and generically.

The Serde ecosystem consists of data structures that know how to serialize
and deserialize themselves along with data formats that know how to
serialize and deserialize other things. Serde provides the layer by which
these two groups interact with each other, allowing any supported data
structure to be serialized and deserialized using any supported data format.

See the Serde website <https://serde.rs> for additional documentation and
usage examples.

### serde › Design

Where many other languages rely on runtime reflection for serializing data,
Serde is instead built on Rust's powerful trait system. A data structure
that knows how to serialize and deserialize itself is one that implements
Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive
attribute to automatically generate implementations at compile time). This
avoids any overhead of reflection or runtime type information. In fact in
many situations the interaction between data structure and data format can
be completely optimized away by the Rust compiler, leaving Serde
serialization to perform the same speed as a handwritten serializer for the
specific selection of data structure and data format.

### serde › Data formats

The following is a partial list of data formats that have been implemented
for Serde by the community.

- [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs.
- [Postcard], a no\_std and embedded-systems friendly compact binary format.
- [CBOR], a Concise Binary Object Representation designed for small message
  size without the need for version negotiation.
- [YAML], a self-proclaimed human-friendly configuration language that ain't
  markup language.
- [MessagePack], an efficient binary format that resembles a compact JSON.
- [TOML], a minimal configuration format used by [Cargo].
- [Pickle], a format common in the Python world.
- [RON], a Rusty Object Notation.
- [BSON], the data storage and network transfer format used by MongoDB.
- [Avro], a binary format used within Apache Hadoop, with support for schema
  definition.
- [JSON5], a superset of JSON including some productions from ES5.
- [URL] query strings, in the x-www-form-urlencoded format.
- [Starlark], the format used for describing build targets by the Bazel and
  Buck build systems. *(serialization only)*
- [Envy], a way to deserialize environment variables into Rust structs.
  *(deserialization only)*
- [Envy Store], a way to deserialize [AWS Parameter Store] parameters into
  Rust structs. *(deserialization only)*
- [S-expressions], the textual representation of code and data used by the
  Lisp language family.
- [D-Bus]'s binary wire format.
- [FlexBuffers], the schemaless cousin of Google's FlatBuffers zero-copy
  serialization format.
- [Bencode], a simple binary format used in the BitTorrent protocol.
- [Token streams], for processing Rust procedural macro input.
  *(deserialization only)*
- [DynamoDB Items], the format used by [rusoto_dynamodb] to transfer data to
  and from DynamoDB.
- [Hjson], a syntax extension to JSON designed around human reading and
  editing. *(deserialization only)*
- [CSV], Comma-separated values is a tabular text file format.

[JSON]: https://github.com/serde-rs/json
[Postcard]: https://github.com/jamesmunns/postcard
[CBOR]: https://github.com/enarx/ciborium
[YAML]: https://github.com/dtolnay/serde-yaml
[MessagePack]: https://github.com/3Hren/msgpack-rust
[TOML]: https://docs.rs/toml
[Pickle]: https://github.com/birkenfeld/serde-pickle
[RON]: https://github.com/ron-rs/ron
[BSON]: https://github.com/mongodb/bson-rust
[Avro]: https://docs.rs/apache-avro
[JSON5]: https://github.com/callum-oakley/json5-rs
[URL]: https://docs.rs/serde_qs
[Starlark]: https://github.com/dtolnay/serde-starlark
[Envy]: https://github.com/softprops/envy
[Envy Store]: https://github.com/softprops/envy-store
[Cargo]: https://doc.rust-lang.org/cargo/reference/manifest.html
[AWS Parameter Store]: https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html
[S-expressions]: https://github.com/rotty/lexpr-rs
[D-Bus]: https://docs.rs/zvariant
[FlexBuffers]: https://github.com/google/flatbuffers/tree/master/rust/flexbuffers
[Bencode]: https://github.com/P3KI/bendy
[Token streams]: https://github.com/oxidecomputer/serde_tokenstream
[DynamoDB Items]: https://docs.rs/serde_dynamo
[rusoto_dynamodb]: https://docs.rs/rusoto_dynamodb
[Hjson]: https://github.com/Canop/deser-hjson
[CSV]: https://docs.rs/csv

## serde::de (module)

Generic data structure deserialization framework.

The two most important traits in this module are [`Deserialize`] and
[`Deserializer`].

 - **A type that implements `Deserialize` is a data structure** that can be
   deserialized from any data format supported by Serde, and conversely
 - **A type that implements `Deserializer` is a data format** that can
   deserialize any data structure supported by Serde.

### serde::de (module) › The Deserialize trait

Serde provides [`Deserialize`] implementations for many Rust primitive and
standard library types. The complete list is below. All of these can be
deserialized using Serde out of the box.

Additionally, Serde provides a procedural macro called [`serde_derive`] to
automatically generate [`Deserialize`] implementations for structs and enums
in your program. See the [derive section of the manual] for how to use this.

In rare cases it may be necessary to implement [`Deserialize`] manually for
some type in your program. See the [Implementing `Deserialize`] section of
the manual for more about this.

Third-party crates may provide [`Deserialize`] implementations for types
that they expose. For example the [`linked-hash-map`] crate provides a
[`LinkedHashMap<K, V>`] type that is deserializable by Serde because the
crate provides an implementation of [`Deserialize`] for it.

### serde::de (module) › The Deserializer trait

[`Deserializer`] implementations are provided by third-party crates, for
example [`serde_json`], [`serde_yaml`] and [`postcard`].

A partial list of well-maintained formats is given on the [Serde
website][data formats].

### serde::de (module) › Implementations of Deserialize provided by Serde

This is a slightly different set of types than what is supported for
serialization. Some types can be serialized by Serde but not deserialized.
One example is `OsStr`.

 - **Primitive types**:
   - bool
   - i8, i16, i32, i64, i128, isize
   - u8, u16, u32, u64, u128, usize
   - f32, f64
   - char
 - **Compound types**:
   - \[T; 0\] through \[T; 32\]
   - tuples up to size 16
 - **Common standard library types**:
   - String
   - Option\<T\>
   - Result\<T, E\>
   - PhantomData\<T\>
 - **Wrapper types**:
   - Box\<T\>
   - Box\<\[T\]\>
   - Box\<str\>
   - Cow\<'a, T\>
   - Cell\<T\>
   - RefCell\<T\>
   - Mutex\<T\>
   - RwLock\<T\>
   - Rc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*
   - Arc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*
 - **Collection types**:
   - BTreeMap\<K, V\>
   - BTreeSet\<T\>
   - BinaryHeap\<T\>
   - HashMap\<K, V, H\>
   - HashSet\<T, H\>
   - LinkedList\<T\>
   - VecDeque\<T\>
   - Vec\<T\>
 - **Zero-copy types**:
   - &str
   - &\[u8\]
 - **FFI types**:
   - CString
   - Box\<CStr\>
   - OsString
 - **Miscellaneous standard library types**:
   - Duration
   - SystemTime
   - Path
   - PathBuf
   - Range\<T\>
   - RangeInclusive\<T\>
   - Bound\<T\>
   - num::NonZero*
   - `!` *(unstable)*
 - **Net types**:
   - IpAddr
   - Ipv4Addr
   - Ipv6Addr
   - SocketAddr
   - SocketAddrV4
   - SocketAddrV6

[Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html
[`Deserialize`]: crate::Deserialize
[`Deserializer`]: crate::Deserializer
[`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
[`postcard`]: https://github.com/jamesmunns/postcard
[`linked-hash-map`]: https://crates.io/crates/linked-hash-map
[`serde_derive`]: https://crates.io/crates/serde_derive
[`serde_json`]: https://github.com/serde-rs/json
[`serde_yaml`]: https://github.com/dtolnay/serde-yaml
[derive section of the manual]: https://serde.rs/derive.html
[data formats]: https://serde.rs/#data-formats

## serde::de::value (module)

Building blocks for deserializing basic values using the `IntoDeserializer`
trait.

```edition2021
use serde::de::{value, Deserialize, IntoDeserializer};
use serde_derive::Deserialize;
use std::str::FromStr;

#[derive(Deserialize)]
enum Setting {
    On,
    Off,
}

impl FromStr for Setting {
    type Err = value::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::deserialize(s.into_deserializer())
    }
}
```

## serde::ser (module)

Generic data structure serialization framework.

The two most important traits in this module are [`Serialize`] and
[`Serializer`].

 - **A type that implements `Serialize` is a data structure** that can be
   serialized to any data format supported by Serde, and conversely
 - **A type that implements `Serializer` is a data format** that can
   serialize any data structure supported by Serde.

### serde::ser (module) › The Serialize trait

Serde provides [`Serialize`] implementations for many Rust primitive and
standard library types. The complete list is below. All of these can be
serialized using Serde out of the box.

Additionally, Serde provides a procedural macro called [`serde_derive`] to
automatically generate [`Serialize`] implementations for structs and enums
in your program. See the [derive section of the manual] for how to use this.

In rare cases it may be necessary to implement [`Serialize`] manually for
some type in your program. See the [Implementing `Serialize`] section of the
manual for more about this.

Third-party crates may provide [`Serialize`] implementations for types that
they expose. For example the [`linked-hash-map`] crate provides a
[`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate
provides an implementation of [`Serialize`] for it.

### serde::ser (module) › The Serializer trait

[`Serializer`] implementations are provided by third-party crates, for
example [`serde_json`], [`serde_yaml`] and [`postcard`].

A partial list of well-maintained formats is given on the [Serde
website][data formats].

### serde::ser (module) › Implementations of Serialize provided by Serde

 - **Primitive types**:
   - bool
   - i8, i16, i32, i64, i128, isize
   - u8, u16, u32, u64, u128, usize
   - f32, f64
   - char
   - str
   - &T and &mut T
 - **Compound types**:
   - \[T\]
   - \[T; 0\] through \[T; 32\]
   - tuples up to size 16
 - **Common standard library types**:
   - String
   - Option\<T\>
   - Result\<T, E\>
   - PhantomData\<T\>
 - **Wrapper types**:
   - Box\<T\>
   - Cow\<'a, T\>
   - Cell\<T\>
   - RefCell\<T\>
   - Mutex\<T\>
   - RwLock\<T\>
   - Rc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*
   - Arc\<T\>&emsp;*(if* features = \["rc"\] *is enabled)*
 - **Collection types**:
   - BTreeMap\<K, V\>
   - BTreeSet\<T\>
   - BinaryHeap\<T\>
   - HashMap\<K, V, H\>
   - HashSet\<T, H\>
   - LinkedList\<T\>
   - VecDeque\<T\>
   - Vec\<T\>
 - **FFI types**:
   - CStr
   - CString
   - OsStr
   - OsString
 - **Miscellaneous standard library types**:
   - Duration
   - SystemTime
   - Path
   - PathBuf
   - Range\<T\>
   - RangeInclusive\<T\>
   - Bound\<T\>
   - num::NonZero*
   - `!` *(unstable)*
 - **Net types**:
   - IpAddr
   - Ipv4Addr
   - Ipv6Addr
   - SocketAddr
   - SocketAddrV4
   - SocketAddrV6

[Implementing `Serialize`]: https://serde.rs/impl-serialize.html
[`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
[`Serialize`]: crate::Serialize
[`Serializer`]: crate::Serializer
[`postcard`]: https://github.com/jamesmunns/postcard
[`linked-hash-map`]: https://crates.io/crates/linked-hash-map
[`serde_derive`]: https://crates.io/crates/serde_derive
[`serde_json`]: https://github.com/serde-rs/json
[`serde_yaml`]: https://github.com/dtolnay/serde-yaml
[derive section of the manual]: https://serde.rs/derive.html
[data formats]: https://serde.rs/#data-formats

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

Deserializing a data structure containing `Arc` will not attempt to
deduplicate `Arc` references to the same data. Every deserialized `Arc`
will end up with a strong count of 1.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

Deserializing a data structure containing `Rc` will not attempt to
deduplicate `Rc` references to the same data. Every deserialized `Rc`
will end up with a strong count of 1.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

Serializing a data structure containing `Arc` will serialize a copy of
the contents of the `Arc` each time the `Arc` is referenced within the
data structure. Serialization will not attempt to deduplicate these
repeated data.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

Serializing a data structure containing `Rc` will serialize a copy of
the contents of the `Rc` each time the `Rc` is referenced within the
data structure. Serialization will not attempt to deduplicate these
repeated data.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
`Weak<T>` has a reference count of 0 and cannot be upgraded.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This impl requires the [`"rc"`] Cargo feature of Serde. The resulting
`Weak<T>` has a reference count of 0 and cannot be upgraded.

[`"rc"`]: https://serde.rs/feature-flags.html#-features-rc

## serde (impl)

This trait is implemented for tuples up to 16 items long.

## serde (impl)

This trait is implemented for tuples up to 16 items long.

## serde (impl)

```edition2021
use serde::ser::Serialize;
use serde_derive::Serialize;
use std::fmt::{self, Display};

#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum MessageType {
    StartRequest,
    EndRequest,
}

impl Display for MessageType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.serialize(f)
    }
}
```

## serde (use)

Derive macro available if serde is built with `features = ["derive"]`.

## serde (use)

Derive macro available if serde is built with `features = ["derive"]`.

## serde::Deserializer (assoc_type)

The type of the deserializer being converted into.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

Must match the `Error` type of our `Serializer`.

## serde::Error (assoc_type)

The error type that can be returned if some error occurs during
deserialization.

## serde::Error (assoc_type)

The error type that can be returned if some error occurs during
deserialization.

## serde::Error (assoc_type)

The error type that can be returned if some error occurs during
deserialization.

## serde::Error (assoc_type)

The error type that can be returned if some error occurs during
deserialization.

## serde::Error (assoc_type)

The error type that can be returned if some error occurs during
deserialization. Must match the error type of our `EnumAccess`.

## serde::Error (assoc_type)

The error type when some error occurs during serialization.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

Must match the `Ok` type of our `Serializer`.

## serde::Ok (assoc_type)

The output type produced by this `Serializer` during successful
serialization. Most serializers that produce text or binary output
should set `Ok = ()` and serialize into an [`io::Write`] or buffer
contained within the `Serializer` instance. Serializers that build
in-memory data structures may be simplified by using `Ok` to propagate
the data structure around.

[`io::Write`]: std::io::Write

## serde::SerializeMap (assoc_type)

Type returned from [`serialize_map`] for serializing the content of the
map.

[`serialize_map`]: #tymethod.serialize_map

## serde::SerializeSeq (assoc_type)

Type returned from [`serialize_seq`] for serializing the content of the
sequence.

[`serialize_seq`]: #tymethod.serialize_seq

## serde::SerializeStruct (assoc_type)

Type returned from [`serialize_struct`] for serializing the content of
the struct.

[`serialize_struct`]: #tymethod.serialize_struct

## serde::SerializeStructVariant (assoc_type)

Type returned from [`serialize_struct_variant`] for serializing the
content of the struct variant.

[`serialize_struct_variant`]: #tymethod.serialize_struct_variant

## serde::SerializeTuple (assoc_type)

Type returned from [`serialize_tuple`] for serializing the content of
the tuple.

[`serialize_tuple`]: #tymethod.serialize_tuple

## serde::SerializeTupleStruct (assoc_type)

Type returned from [`serialize_tuple_struct`] for serializing the
content of the tuple struct.

[`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct

## serde::SerializeTupleVariant (assoc_type)

Type returned from [`serialize_tuple_variant`] for serializing the
content of the tuple variant.

[`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant

## serde::Value (assoc_type)

The type produced by using this seed.

## serde::Value (assoc_type)

The value produced by this visitor.

## serde::Variant (assoc_type)

The `Visitor` that will be used to deserialize the content of the enum
variant.

## serde::collect_map (function)

Collect an iterator as a map.

The default implementation serializes each pair yielded by the iterator
using [`serialize_map`]. Implementors should not need to override this
method.

```edition2021
use serde::{Serialize, Serializer};
use std::collections::BTreeSet;

struct MapToUnit {
    keys: BTreeSet<i32>,
}

// Serializes as a map in which the values are all unit.
impl Serialize for MapToUnit {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_map(self.keys.iter().map(|k| (k, ())))
    }
}
```

[`serialize_map`]: #tymethod.serialize_map

## serde::collect_seq (function)

Collect an iterator as a sequence.

The default implementation serializes each item yielded by the iterator
using [`serialize_seq`]. Implementors should not need to override this
method.

```edition2021
use serde::{Serialize, Serializer};

struct SecretlyOneHigher {
    data: Vec<i32>,
}

impl Serialize for SecretlyOneHigher {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_seq(self.data.iter().map(|x| x + 1))
    }
}
```

[`serialize_seq`]: #tymethod.serialize_seq

## serde::collect_str (function)

Serialize a string produced by an implementation of `Display`.

The default implementation builds a heap-allocated [`String`] and
delegates to [`serialize_str`]. Serializers are encouraged to provide a
more efficient implementation if possible.

```edition2021
# struct DateTime;
#
# impl DateTime {
#     fn naive_local(&self) -> () { () }
#     fn offset(&self) -> () { () }
# }
#
use serde::{Serialize, Serializer};

impl Serialize for DateTime {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_str(&format_args!("{:?}{:?}", self.naive_local(), self.offset()))
    }
}
```

[`serialize_str`]: Self::serialize_str

## serde::custom (function)

Raised when there is general error when deserializing a type.

The message should not be capitalized and should not end with a period.

```edition2021
# use std::str::FromStr;
#
# struct IpAddr;
#
# impl FromStr for IpAddr {
#     type Err = String;
#
#     fn from_str(_: &str) -> Result<Self, String> {
#         unimplemented!()
#     }
# }
#
use serde::de::{self, Deserialize, Deserializer};

impl<'de> Deserialize<'de> for IpAddr {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(de::Error::custom)
    }
}
```

## serde::custom (function)

Used when a [`Serialize`] implementation encounters any error
while serializing a type.

The message should not be capitalized and should not end with a
period.

For example, a filesystem [`Path`] may refuse to serialize
itself if it contains invalid UTF-8 data.

```edition2021
# struct Path;
#
# impl Path {
#     fn to_str(&self) -> Option<&str> {
#         unimplemented!()
#     }
# }
#
use serde::ser::{self, Serialize, Serializer};

impl Serialize for Path {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self.to_str() {
            Some(s) => serializer.serialize_str(s),
            None => Err(ser::Error::custom("path contains invalid UTF-8 characters")),
        }
    }
}
```

[`Path`]: std::path::Path
[`Serialize`]: crate::Serialize

## serde::de::Deserialize (trait)

A **data structure** that can be deserialized from any data format supported
by Serde.

Serde provides `Deserialize` implementations for many Rust primitive and
standard library types. The complete list is [here][crate::de]. All of these
can be deserialized using Serde out of the box.

Additionally, Serde provides a procedural macro called `serde_derive` to
automatically generate `Deserialize` implementations for structs and enums
in your program. See the [derive section of the manual][derive] for how to
use this.

In rare cases it may be necessary to implement `Deserialize` manually for
some type in your program. See the [Implementing
`Deserialize`][impl-deserialize] section of the manual for more about this.

Third-party crates may provide `Deserialize` implementations for types that
they expose. For example the `linked-hash-map` crate provides a
`LinkedHashMap<K, V>` type that is deserializable by Serde because the crate
provides an implementation of `Deserialize` for it.

[derive]: https://serde.rs/derive.html
[impl-deserialize]: https://serde.rs/impl-deserialize.html

### serde::de::Deserialize (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by `Self` when deserialized. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

## serde::de::DeserializeOwned (trait)

A data structure that can be deserialized without borrowing any data from
the deserializer.

This is primarily useful for trait bounds on functions. For example a
`from_str` function may be able to deserialize a data structure that borrows
from the input string, but a `from_reader` function may only deserialize
owned data.

```edition2021
# use serde::de::{Deserialize, DeserializeOwned};
# use std::io::{Read, Result};
#
# trait Ignore {
fn from_str<'a, T>(s: &'a str) -> Result<T>
where
    T: Deserialize<'a>;

fn from_reader<R, T>(rdr: R) -> Result<T>
where
    R: Read,
    T: DeserializeOwned;
# }
```

### serde::de::DeserializeOwned (trait) › Lifetime

The relationship between `Deserialize` and `DeserializeOwned` in trait
bounds is explained in more detail on the page [Understanding deserializer
lifetimes].

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

## serde::de::DeserializeSeed (trait)

`DeserializeSeed` is the stateful form of the `Deserialize` trait. If you
ever find yourself looking for a way to pass data into a `Deserialize` impl,
this trait is the way to do it.

As one example of stateful deserialization consider deserializing a JSON
array into an existing buffer. Using the `Deserialize` trait we could
deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated
`Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated
buffer. Using `DeserializeSeed` instead makes this possible as in the
example code below.

The canonical API for stateless deserialization looks like this:

```edition2021
# use serde::Deserialize;
#
# enum Error {}
#
fn func<'de, T: Deserialize<'de>>() -> Result<T, Error>
# {
#     unimplemented!()
# }
```

Adjusting an API like this to support stateful deserialization is a matter
of accepting a seed as input:

```edition2021
# use serde::de::DeserializeSeed;
#
# enum Error {}
#
fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error>
# {
#     let _ = seed;
#     unimplemented!()
# }
```

In practice the majority of deserialization is stateless. An API expecting a
seed can be appeased by passing `std::marker::PhantomData` as a seed in the
case of stateless deserialization.

### serde::de::DeserializeSeed (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by `Self::Value` when deserialized. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::DeserializeSeed (trait) › Example

Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need
to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`.
Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we
would like to allocate a single `Vec<T>` and then deserialize each subarray
into it. This requires stateful deserialization using the `DeserializeSeed`
trait.

```edition2021
use serde::de::{Deserialize, DeserializeSeed, Deserializer, SeqAccess, Visitor};
use std::fmt;
use std::marker::PhantomData;

// A DeserializeSeed implementation that uses stateful deserialization to
// append array elements onto the end of an existing vector. The preexisting
// state ("seed") in this case is the Vec<T>. The `deserialize` method of
// `ExtendVec` will be traversing the inner arrays of the JSON input and
// appending each integer into the existing Vec.
struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>);

impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T>
where
    T: Deserialize<'de>,
{
    // The return type of the `deserialize` method. This implementation
    // appends onto an existing vector but does not create any new data
    // structure, so the return type is ().
    type Value = ();

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        // Visitor implementation that will walk an inner array of the JSON
        // input.
        struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>);

        impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T>
        where
            T: Deserialize<'de>,
        {
            type Value = ();

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "an array of integers")
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error>
            where
                A: SeqAccess<'de>,
            {
                // Decrease the number of reallocations if there are many elements
                if let Some(size_hint) = seq.size_hint() {
                    self.0.reserve(size_hint);
                }

                // Visit each element in the inner array and push it onto
                // the existing vector.
                while let Some(elem) = seq.next_element()? {
                    self.0.push(elem);
                }
                Ok(())
            }
        }

        deserializer.deserialize_seq(ExtendVecVisitor(self.0))
    }
}

// Visitor implementation that will walk the outer array of the JSON input.
struct FlattenedVecVisitor<T>(PhantomData<T>);

impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T>
where
    T: Deserialize<'de>,
{
    // This Visitor constructs a single Vec<T> to hold the flattened
    // contents of the inner arrays.
    type Value = Vec<T>;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "an array of arrays")
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error>
    where
        A: SeqAccess<'de>,
    {
        // Create a single Vec to hold the flattened contents.
        let mut vec = Vec::new();

        // Each iteration through this loop is one inner array.
        while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? {
            // Nothing to do; inner array has been appended into `vec`.
        }

        // Return the finished vec.
        Ok(vec)
    }
}

# fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
# where
#     D: Deserializer<'de>,
# {
let visitor = FlattenedVecVisitor(PhantomData);
let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?;
#     Ok(())
# }
```

## serde::de::Deserializer (trait)

A **data format** that can deserialize any data structure supported by
Serde.

The role of this trait is to define the deserialization half of the [Serde
data model], which is a way to categorize every Rust data type into one of
29 possible types. Each method of the `Deserializer` trait corresponds to one
of the types of the data model.

Implementations of `Deserialize` map themselves into this data model by
passing to the `Deserializer` a `Visitor` implementation that can receive
these various types.

The types that make up the Serde data model are:

 - **14 primitive types**
   - bool
   - i8, i16, i32, i64, i128
   - u8, u16, u32, u64, u128
   - f32, f64
   - char
 - **string**
   - UTF-8 bytes with a length and no null terminator.
   - When serializing, all strings are handled equally. When deserializing,
     there are three flavors of strings: transient, owned, and borrowed.
 - **byte array** - \[u8\]
   - Similar to strings, during deserialization byte arrays can be
     transient, owned, or borrowed.
 - **option**
   - Either none or some value.
 - **unit**
   - The type of `()` in Rust. It represents an anonymous value containing
     no data.
 - **unit_struct**
   - For example `struct Unit` or `PhantomData<T>`. It represents a named
     value containing no data.
 - **unit_variant**
   - For example the `E::A` and `E::B` in `enum E { A, B }`.
 - **newtype_struct**
   - For example `struct Millimeters(u8)`.
 - **newtype_variant**
   - For example the `E::N` in `enum E { N(u8) }`.
 - **seq**
   - A variably sized heterogeneous sequence of values, for example `Vec<T>`
     or `HashSet<T>`. When serializing, the length may or may not be known
     before iterating through all the data. When deserializing, the length
     is determined by looking at the serialized data.
 - **tuple**
   - A statically sized heterogeneous sequence of values for which the
     length will be known at deserialization time without looking at the
     serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or
     `[u64; 10]`.
 - **tuple_struct**
   - A named tuple, for example `struct Rgb(u8, u8, u8)`.
 - **tuple_variant**
   - For example the `E::T` in `enum E { T(u8, u8) }`.
 - **map**
   - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
 - **struct**
   - A heterogeneous key-value pairing in which the keys are strings and
     will be known at deserialization time without looking at the serialized
     data, for example `struct S { r: u8, g: u8, b: u8 }`.
 - **struct_variant**
   - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.

The `Deserializer` trait supports two entry point styles which enables
different kinds of deserialization.

1. The `deserialize_any` method. Self-describing data formats like JSON are
   able to look at the serialized data and tell what it represents. For
   example the JSON deserializer may see an opening curly brace (`{`) and
   know that it is seeing a map. If the data format supports
   `Deserializer::deserialize_any`, it will drive the Visitor using whatever
   type it sees in the input. JSON uses this approach when deserializing
   `serde_json::Value` which is an enum that can represent any JSON
   document. Without knowing what is in a JSON document, we can deserialize
   it to `serde_json::Value` by going through
   `Deserializer::deserialize_any`.

2. The various `deserialize_*` methods. Non-self-describing formats like
   Postcard need to be told what is in the input in order to deserialize it.
   The `deserialize_*` methods are hints to the deserializer for how to
   interpret the next piece of input. Non-self-describing formats are not
   able to deserialize something like `serde_json::Value` which relies on
   `Deserializer::deserialize_any`.

When implementing `Deserialize`, you should avoid relying on
`Deserializer::deserialize_any` unless you need to be told by the
Deserializer what type is in the input. Know that relying on
`Deserializer::deserialize_any` means your data type will be able to
deserialize from self-describing formats only, ruling out Postcard and many
others.

[Serde data model]: https://serde.rs/data-model.html

### serde::de::Deserializer (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed from the input when deserializing. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::Deserializer (trait) › Example implementation

The [example data format] presented on the website contains example code for
a basic JSON `Deserializer`.

[example data format]: https://serde.rs/data-format.html

## serde::de::Deserializer::deserialize_any (function)

Require the `Deserializer` to figure out how to drive the visitor based
on what data type is in the input.

When implementing `Deserialize`, you should avoid relying on
`Deserializer::deserialize_any` unless you need to be told by the
Deserializer what type is in the input. Know that relying on
`Deserializer::deserialize_any` means your data type will be able to
deserialize from self-describing formats only, ruling out Postcard and
many others.

## serde::de::EnumAccess (trait)

Provides a `Visitor` access to the data of an enum in the input.

`EnumAccess` is created by the `Deserializer` and passed to the
`Visitor` in order to identify which variant of an enum to deserialize.

### serde::de::EnumAccess (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by the deserialized enum variant. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::EnumAccess (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `EnumAccess` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::de::Error (trait)

The `Error` trait allows `Deserialize` implementations to create descriptive
error messages belonging to the `Deserializer` against which they are
currently running.

Every `Deserializer` declares an `Error` type that encompasses both
general-purpose deserialization errors as well as errors specific to the
particular deserialization format. For example the `Error` type of
`serde_json` can represent errors like an invalid JSON escape sequence or an
unterminated string literal, in addition to the error cases that are part of
this trait.

Most deserializers should only need to provide the `Error::custom` method
and inherit the default behavior for the other methods.

### serde::de::Error (trait) › Example implementation

The [example data format] presented on the website shows an error
type appropriate for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::de::Expected (trait)

`Expected` represents an explanation of what data a `Visitor` was expecting
to receive.

This is used as an argument to the `invalid_type`, `invalid_value`, and
`invalid_length` methods of the `Error` trait to build error messages. The
message should be a noun or noun phrase that completes the sentence "This
Visitor expects to receive ...", for example the message could be "an
integer between 0 and 64". The message should not be capitalized and should
not end with a period.

Within the context of a `Visitor` implementation, the `Visitor` itself
(`&self`) is an implementation of this trait.

```edition2021
# use serde::de::{self, Unexpected, Visitor};
# use std::fmt;
#
# struct Example;
#
# impl<'de> Visitor<'de> for Example {
#     type Value = ();
#
#     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         write!(formatter, "definitely not a boolean")
#     }
#
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
    E: de::Error,
{
    Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
}
# }
```

Outside of a `Visitor`, `&"..."` can be used.

```edition2021
# use serde::de::{self, Unexpected};
#
# fn example<E>() -> Result<(), E>
# where
#     E: de::Error,
# {
#     let v = true;
return Err(de::Error::invalid_type(
    Unexpected::Bool(v),
    &"a negative integer",
));
# }
```

## serde::de::IntoDeserializer (trait)

Converts an existing value into a `Deserializer` from which other values can
be deserialized.

### serde::de::IntoDeserializer (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed from the resulting `Deserializer`. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::IntoDeserializer (trait) › Example

```edition2021
use serde::de::{value, Deserialize, IntoDeserializer};
use serde_derive::Deserialize;
use std::str::FromStr;

#[derive(Deserialize)]
enum Setting {
    On,
    Off,
}

impl FromStr for Setting {
    type Err = value::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::deserialize(s.into_deserializer())
    }
}
```

## serde::de::MapAccess (trait)

Provides a `Visitor` access to each entry of a map in the input.

This is a trait that a `Deserializer` passes to a `Visitor` implementation.

### serde::de::MapAccess (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by deserialized map entries. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::MapAccess (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `MapAccess` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::de::SeqAccess (trait)

Provides a `Visitor` access to each element of a sequence in the input.

This is a trait that a `Deserializer` passes to a `Visitor` implementation,
which deserializes each item in a sequence.

### serde::de::SeqAccess (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by deserialized sequence elements. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::SeqAccess (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SeqAccess` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::de::Unexpected (enum)

`Unexpected` represents an unexpected invocation of any one of the `Visitor`
trait methods.

This is used as an argument to the `invalid_type`, `invalid_value`, and
`invalid_length` methods of the `Error` trait to build error messages.

```edition2021
# use std::fmt;
#
# use serde::de::{self, Unexpected, Visitor};
#
# struct Example;
#
# impl<'de> Visitor<'de> for Example {
#     type Value = ();
#
#     fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         write!(formatter, "definitely not a boolean")
#     }
#
fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
where
    E: de::Error,
{
    Err(de::Error::invalid_type(Unexpected::Bool(v), &self))
}
# }
```

## serde::de::Unexpected::Bool (variant)

The input contained a boolean value that was not expected.

## serde::de::Unexpected::Bytes (variant)

The input contained a `&[u8]` or `Vec<u8>` that was not expected.

## serde::de::Unexpected::Char (variant)

The input contained a `char` that was not expected.

## serde::de::Unexpected::Enum (variant)

The input contained an enum that was not expected.

## serde::de::Unexpected::Float (variant)

The input contained a floating point `f32` or `f64` that was not
expected.

## serde::de::Unexpected::Map (variant)

The input contained a map that was not expected.

## serde::de::Unexpected::NewtypeStruct (variant)

The input contained a newtype struct that was not expected.

## serde::de::Unexpected::NewtypeVariant (variant)

The input contained a newtype variant that was not expected.

## serde::de::Unexpected::Option (variant)

The input contained an `Option<T>` that was not expected.

## serde::de::Unexpected::Other (variant)

A message stating what uncategorized thing the input contained that was
not expected.

The message should be a noun or noun phrase, not capitalized and without
a period. An example message is "unoriginal superhero".

## serde::de::Unexpected::Seq (variant)

The input contained a sequence that was not expected.

## serde::de::Unexpected::Signed (variant)

The input contained a signed integer `i8`, `i16`, `i32` or `i64` that
was not expected.

## serde::de::Unexpected::Str (variant)

The input contained a `&str` or `String` that was not expected.

## serde::de::Unexpected::StructVariant (variant)

The input contained a struct variant that was not expected.

## serde::de::Unexpected::TupleVariant (variant)

The input contained a tuple variant that was not expected.

## serde::de::Unexpected::Unit (variant)

The input contained a unit `()` that was not expected.

## serde::de::Unexpected::UnitVariant (variant)

The input contained a unit variant that was not expected.

## serde::de::Unexpected::Unsigned (variant)

The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that
was not expected.

## serde::de::VariantAccess (trait)

`VariantAccess` is a visitor that is created by the `Deserializer` and
passed to the `Deserialize` to deserialize the content of a particular enum
variant.

### serde::de::VariantAccess (trait) › Lifetime

The `'de` lifetime of this trait is the lifetime of data that may be
borrowed by the deserialized enum variant. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::VariantAccess (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `VariantAccess` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::de::Visitor (trait)

This trait represents a visitor that walks through a deserializer.

### serde::de::Visitor (trait) › Lifetime

The `'de` lifetime of this trait is the requirement for lifetime of data
that may be borrowed by `Self::Value`. See the page [Understanding
deserializer lifetimes] for a more detailed explanation of these lifetimes.

[Understanding deserializer lifetimes]: https://serde.rs/lifetimes.html

### serde::de::Visitor (trait) › Example

```edition2021
# use serde::de::{self, Unexpected, Visitor};
# use std::fmt;
#
/// A visitor that deserializes a long string - a string containing at least
/// some minimum number of bytes.
struct LongString {
    min: usize,
}

impl<'de> Visitor<'de> for LongString {
    type Value = String;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "a string containing at least {} bytes", self.min)
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        if s.len() >= self.min {
            Ok(s.to_owned())
        } else {
            Err(de::Error::invalid_value(Unexpected::Str(s), &self))
        }
    }
}
```

## serde::de::Visitor::visit_borrowed_bytes (function)

The input contains a byte array that lives at least as long as the
`Deserializer`.

This enables zero-copy deserialization of bytes in some formats. For
example Postcard data containing bytes can be deserialized with zero
copying into a `&'a [u8]` as long as the input data outlives `'a`.

The default implementation forwards to `visit_bytes`.

## serde::de::Visitor::visit_bytes (function)

The input contains a byte array. The lifetime of the byte array is
ephemeral and it may be destroyed after this method returns.

This method allows the `Deserializer` to avoid a copy by retaining
ownership of any buffered data. `Deserialize` implementations that do
not benefit from taking ownership of `Vec<u8>` data should indicate that
to the deserializer by using `Deserializer::deserialize_bytes` rather
than `Deserializer::deserialize_byte_buf`.

It is never correct to implement `visit_byte_buf` without implementing
`visit_bytes`. Implement neither, both, or just `visit_bytes`.

## serde::de::ignored_any::IgnoredAny (struct)

An efficient way of discarding data from a deserializer.

Think of this like `serde_json::Value` in that it can be deserialized from
any type, except that it does not store any information about the data that
gets deserialized.

```edition2021
use serde::de::{
    self, Deserialize, DeserializeSeed, Deserializer, IgnoredAny, SeqAccess, Visitor,
};
use std::fmt;
use std::marker::PhantomData;

/// A seed that can be used to deserialize only the `n`th element of a sequence
/// while efficiently discarding elements of any type before or after index `n`.
///
/// For example to deserialize only the element at index 3:
///
/// ```
/// NthElement::new(3).deserialize(deserializer)
/// ```
pub struct NthElement<T> {
    n: usize,
    marker: PhantomData<T>,
}

impl<T> NthElement<T> {
    pub fn new(n: usize) -> Self {
        NthElement {
            n: n,
            marker: PhantomData,
        }
    }
}

impl<'de, T> Visitor<'de> for NthElement<T>
where
    T: Deserialize<'de>,
{
    type Value = T;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "a sequence in which we care about element {}",
            self.n
        )
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        // Skip over the first `n` elements.
        for i in 0..self.n {
            // It is an error if the sequence ends before we get to element `n`.
            if seq.next_element::<IgnoredAny>()?.is_none() {
                return Err(de::Error::invalid_length(i, &self));
            }
        }

        // Deserialize the one we care about.
        let nth = match seq.next_element()? {
            Some(nth) => nth,
            None => {
                return Err(de::Error::invalid_length(self.n, &self));
            }
        };

        // Skip over any remaining elements in the sequence after `n`.
        while let Some(IgnoredAny) = seq.next_element()? {
            // ignore
        }

        Ok(nth)
    }
}

impl<'de, T> DeserializeSeed<'de> for NthElement<T>
where
    T: Deserialize<'de>,
{
    type Value = T;

    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_seq(self)
    }
}

# fn example<'de, D>(deserializer: D) -> Result<(), D::Error>
# where
#     D: Deserializer<'de>,
# {
// Deserialize only the sequence element at index 3 from this deserializer.
// The element at index 3 is required to be a string. Elements before and
// after index 3 are allowed to be of any type.
let s: String = NthElement::new(3).deserialize(deserializer)?;
#     Ok(())
# }
```

## serde::de::value::BoolDeserializer (struct)

A deserializer holding
a `bool`.

## serde::de::value::BorrowedBytesDeserializer (struct)

A deserializer holding a `&[u8]` with a lifetime tied to another
deserializer. Always calls [`Visitor::visit_borrowed_bytes`].

## serde::de::value::BorrowedStrDeserializer (struct)

A deserializer holding a `&str` with a lifetime tied to another
deserializer.

## serde::de::value::BytesDeserializer (struct)

A deserializer holding a `&[u8]`. Always calls [`Visitor::visit_bytes`].

## serde::de::value::CharDeserializer (struct)

A deserializer holding
a `char`.

## serde::de::value::CowStrDeserializer (struct)

A deserializer holding a `Cow<str>`.

## serde::de::value::EnumAccessDeserializer (struct)

A deserializer holding an `EnumAccess`.

## serde::de::value::Error (struct)

A minimal representation of all possible errors that can occur using the
`IntoDeserializer` trait.

## serde::de::value::F32Deserializer (struct)

A deserializer holding
an `f32`.

## serde::de::value::F64Deserializer (struct)

A deserializer holding
an `f64`.

## serde::de::value::I128Deserializer (struct)

A deserializer holding
an `i128`.

## serde::de::value::I16Deserializer (struct)

A deserializer holding
an `i16`.

## serde::de::value::I32Deserializer (struct)

A deserializer holding
an `i32`.

## serde::de::value::I64Deserializer (struct)

A deserializer holding
an `i64`.

## serde::de::value::I8Deserializer (struct)

A deserializer holding
an `i8`.

## serde::de::value::IsizeDeserializer (struct)

A deserializer holding
an `isize`.

## serde::de::value::MapAccessDeserializer (struct)

A deserializer holding a `MapAccess`.

## serde::de::value::MapDeserializer (struct)

A deserializer that iterates over a map.

## serde::de::value::NeverDeserializer (struct)

A deserializer that cannot be instantiated.

## serde::de::value::SeqAccessDeserializer (struct)

A deserializer holding a `SeqAccess`.

## serde::de::value::SeqDeserializer (struct)

A deserializer that iterates over a sequence.

## serde::de::value::StrDeserializer (struct)

A deserializer holding a `&str`.

## serde::de::value::StringDeserializer (struct)

A deserializer holding a `String`.

## serde::de::value::U128Deserializer (struct)

A deserializer holding
a `u128`.

## serde::de::value::U16Deserializer (struct)

A deserializer holding
a `u16`.

## serde::de::value::U32Deserializer (struct)

A deserializer holding a `u32`.

## serde::de::value::U64Deserializer (struct)

A deserializer holding
a `u64`.

## serde::de::value::U8Deserializer (struct)

A deserializer holding
a `u8`.

## serde::de::value::UnitDeserializer (struct)

A deserializer holding a `()`.

## serde::de::value::UsizeDeserializer (struct)

A deserializer holding
a `usize`.

## serde::de::value::private::Pair (trait)

Avoid having to restate the generic types on `MapDeserializer`. The
`Iterator::Item` contains enough information to figure out K and V.

## serde::deserialize (function)

Deserialize this value from the given Serde deserializer.

See the [Implementing `Deserialize`][impl-deserialize] section of the
manual for more information about how to implement this method.

[impl-deserialize]: https://serde.rs/impl-deserialize.html

## serde::deserialize (function)

Equivalent to the more common `Deserialize::deserialize` method, except
with some initial piece of data (the seed) passed in.

## serde::deserialize_bool (function)

Hint that the `Deserialize` type is expecting a `bool` value.

## serde::deserialize_byte_buf (function)

Hint that the `Deserialize` type is expecting a byte array and would
benefit from taking ownership of buffered data owned by the
`Deserializer`.

If the `Visitor` would not benefit from taking ownership of `Vec<u8>`
data, indicate that to the `Deserializer` by using `deserialize_bytes`
instead.

## serde::deserialize_bytes (function)

Hint that the `Deserialize` type is expecting a byte array and does not
benefit from taking ownership of buffered data owned by the
`Deserializer`.

If the `Visitor` would benefit from taking ownership of `Vec<u8>` data,
indicate this to the `Deserializer` by using `deserialize_byte_buf`
instead.

## serde::deserialize_char (function)

Hint that the `Deserialize` type is expecting a `char` value.

## serde::deserialize_enum (function)

Hint that the `Deserialize` type is expecting an enum value with a
particular name and possible variants.

## serde::deserialize_f32 (function)

Hint that the `Deserialize` type is expecting a `f32` value.

## serde::deserialize_f64 (function)

Hint that the `Deserialize` type is expecting a `f64` value.

## serde::deserialize_i128 (function)

Hint that the `Deserialize` type is expecting an `i128` value.

The default behavior unconditionally returns an error.

## serde::deserialize_i16 (function)

Hint that the `Deserialize` type is expecting an `i16` value.

## serde::deserialize_i32 (function)

Hint that the `Deserialize` type is expecting an `i32` value.

## serde::deserialize_i64 (function)

Hint that the `Deserialize` type is expecting an `i64` value.

## serde::deserialize_i8 (function)

Hint that the `Deserialize` type is expecting an `i8` value.

## serde::deserialize_identifier (function)

Hint that the `Deserialize` type is expecting the name of a struct
field or the discriminant of an enum variant.

## serde::deserialize_ignored_any (function)

Hint that the `Deserialize` type needs to deserialize a value whose type
doesn't matter because it is ignored.

Deserializers for non-self-describing formats may not support this mode.

## serde::deserialize_map (function)

Hint that the `Deserialize` type is expecting a map of key-value pairs.

## serde::deserialize_newtype_struct (function)

Hint that the `Deserialize` type is expecting a newtype struct with a
particular name.

## serde::deserialize_option (function)

Hint that the `Deserialize` type is expecting an optional value.

This allows deserializers that encode an optional value as a nullable
value to convert the null value into `None` and a regular value into
`Some(value)`.

## serde::deserialize_seq (function)

Hint that the `Deserialize` type is expecting a sequence of values.

## serde::deserialize_str (function)

Hint that the `Deserialize` type is expecting a string value and does
not benefit from taking ownership of buffered data owned by the
`Deserializer`.

If the `Visitor` would benefit from taking ownership of `String` data,
indicate this to the `Deserializer` by using `deserialize_string`
instead.

## serde::deserialize_string (function)

Hint that the `Deserialize` type is expecting a string value and would
benefit from taking ownership of buffered data owned by the
`Deserializer`.

If the `Visitor` would not benefit from taking ownership of `String`
data, indicate that to the `Deserializer` by using `deserialize_str`
instead.

## serde::deserialize_struct (function)

Hint that the `Deserialize` type is expecting a struct with a particular
name and fields.

## serde::deserialize_tuple (function)

Hint that the `Deserialize` type is expecting a sequence of values and
knows how many values there are without looking at the serialized data.

## serde::deserialize_tuple_struct (function)

Hint that the `Deserialize` type is expecting a tuple struct with a
particular name and number of fields.

## serde::deserialize_u128 (function)

Hint that the `Deserialize` type is expecting an `u128` value.

The default behavior unconditionally returns an error.

## serde::deserialize_u16 (function)

Hint that the `Deserialize` type is expecting a `u16` value.

## serde::deserialize_u32 (function)

Hint that the `Deserialize` type is expecting a `u32` value.

## serde::deserialize_u64 (function)

Hint that the `Deserialize` type is expecting a `u64` value.

## serde::deserialize_u8 (function)

Hint that the `Deserialize` type is expecting a `u8` value.

## serde::deserialize_unit (function)

Hint that the `Deserialize` type is expecting a unit value.

## serde::deserialize_unit_struct (function)

Hint that the `Deserialize` type is expecting a unit struct with a
particular name.

## serde::duplicate_field (function)

Raised when a `Deserialize` struct type received more than one of the
same field.

## serde::end (function)

Check for remaining elements after passing a `MapDeserializer` to
`Visitor::visit_map`.

## serde::end (function)

Check for remaining elements after passing a `SeqDeserializer` to
`Visitor::visit_seq`.

## serde::end (function)

Finish serializing a map.

## serde::end (function)

Finish serializing a sequence.

## serde::end (function)

Finish serializing a struct variant.

## serde::end (function)

Finish serializing a struct.

## serde::end (function)

Finish serializing a tuple struct.

## serde::end (function)

Finish serializing a tuple variant.

## serde::end (function)

Finish serializing a tuple.

## serde::expecting (function)

Format a message stating what data this Visitor expects to receive.

This is used in error messages. The message should complete the sentence
"This Visitor expects to receive ...", for example the message could be
"an integer between 0 and 64". The message should not be capitalized and
should not end with a period.

```edition2021
# use std::fmt;
#
# struct S {
#     max: usize,
# }
#
# impl<'de> serde::de::Visitor<'de> for S {
#     type Value = ();
#
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
    write!(formatter, "an integer between 0 and {}", self.max)
}
# }
```

## serde::fmt (function)

Format an explanation of what data was being expected. Same signature as
the `Display` and `Debug` traits.

## serde::forward_to_deserialize_any (macro)

Helper macro when implementing the `Deserializer` part of a new data format
for Serde.

Some [`Deserializer`] implementations for self-describing formats do not
care what hint the [`Visitor`] gives them, they just want to blindly call
the [`Visitor`] method corresponding to the data they can tell is in the
input. This requires repetitive implementations of all the [`Deserializer`]
trait methods.

```edition2021
# use serde::forward_to_deserialize_any;
# use serde::de::{value, Deserializer, Visitor};
#
# struct MyDeserializer;
#
# impl<'de> Deserializer<'de> for MyDeserializer {
#     type Error = value::Error;
#
#     fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     {
#         unimplemented!()
#     }
#
#[inline]
fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
    V: Visitor<'de>,
{
    self.deserialize_any(visitor)
}
#
#     forward_to_deserialize_any! {
#         i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
#         bytes byte_buf option unit unit_struct newtype_struct seq tuple
#         tuple_struct map struct enum identifier ignored_any
#     }
# }
```

The `forward_to_deserialize_any!` macro implements these simple forwarding
methods so that they forward directly to [`Deserializer::deserialize_any`].
You can choose which methods to forward.

```edition2021
# use serde::forward_to_deserialize_any;
# use serde::de::{value, Deserializer, Visitor};
#
# struct MyDeserializer;
#
impl<'de> Deserializer<'de> for MyDeserializer {
#   type Error = value::Error;
#
    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        /* ... */
#       let _ = visitor;
#       unimplemented!()
    }

    forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq tuple
        tuple_struct map struct enum identifier ignored_any
    }
}
```

The macro assumes the convention that your `Deserializer` lifetime parameter
is called `'de` and that the `Visitor` type parameters on each method are
called `V`. A different type parameter and a different lifetime can be
specified explicitly if necessary.

```edition2021
# use serde::forward_to_deserialize_any;
# use serde::de::{value, Deserializer, Visitor};
# use std::marker::PhantomData;
#
# struct MyDeserializer<V>(PhantomData<V>);
#
# impl<'q, V> Deserializer<'q> for MyDeserializer<V> {
#     type Error = value::Error;
#
#     fn deserialize_any<W>(self, visitor: W) -> Result<W::Value, Self::Error>
#     where
#         W: Visitor<'q>,
#     {
#         unimplemented!()
#     }
#
forward_to_deserialize_any! {
    <W: Visitor<'q>>
    bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
    bytes byte_buf option unit unit_struct newtype_struct seq tuple
    tuple_struct map struct enum identifier ignored_any
}
# }
```

[`Deserializer`]: crate::Deserializer
[`Visitor`]: crate::de::Visitor
[`Deserializer::deserialize_any`]: crate::Deserializer::deserialize_any

## serde::into_deserializer (function)

Convert this value into a deserializer.

## serde::invalid_length (function)

Raised when deserializing a sequence or map and the input data contains
too many or too few elements.

The `len` argument is the number of elements encountered. The sequence
or map may have expected more arguments or fewer arguments.

The `exp` argument provides information about what data was being
expected. For example `exp` might say that a tuple of size 6 was
expected.

## serde::invalid_type (function)

Raised when a `Deserialize` receives a type different from what it was
expecting.

The `unexp` argument provides information about what type was received.
This is the type that was present in the input file or other source data
of the Deserializer.

The `exp` argument provides information about what type was being
expected. This is the type that is written in the program.

For example if we try to deserialize a String out of a JSON file
containing an integer, the unexpected type is the integer and the
expected type is the string.

## serde::invalid_value (function)

Raised when a `Deserialize` receives a value of the right type but that
is wrong for some other reason.

The `unexp` argument provides information about what value was received.
This is the value that was present in the input file or other source
data of the Deserializer.

The `exp` argument provides information about what value was being
expected. This is the type that is written in the program.

For example if we try to deserialize a String out of some binary data
that is not valid UTF-8, the unexpected value is the bytes and the
expected value is a string.

## serde::is_human_readable (function)

Determine whether `Deserialize` implementations should expect to
deserialize their human-readable form.

Some types have a human-readable form that may be somewhat expensive to
construct, as well as a binary form that is compact and efficient.
Generally text-based formats like JSON and YAML will prefer to use the
human-readable one and binary formats like Postcard will prefer the
compact one.

```edition2021
# use std::ops::Add;
# use std::str::FromStr;
#
# struct Timestamp;
#
# impl Timestamp {
#     const EPOCH: Timestamp = Timestamp;
# }
#
# impl FromStr for Timestamp {
#     type Err = String;
#     fn from_str(_: &str) -> Result<Self, Self::Err> {
#         unimplemented!()
#     }
# }
#
# struct Duration;
#
# impl Duration {
#     fn seconds(_: u64) -> Self { unimplemented!() }
# }
#
# impl Add<Duration> for Timestamp {
#     type Output = Timestamp;
#     fn add(self, _: Duration) -> Self::Output {
#         unimplemented!()
#     }
# }
#
use serde::de::{self, Deserialize, Deserializer};

impl<'de> Deserialize<'de> for Timestamp {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            // Deserialize from a human-readable string like "2015-05-15T17:01:00Z".
            let s = String::deserialize(deserializer)?;
            Timestamp::from_str(&s).map_err(de::Error::custom)
        } else {
            // Deserialize from a compact binary representation, seconds since
            // the Unix epoch.
            let n = u64::deserialize(deserializer)?;
            Ok(Timestamp::EPOCH + Duration::seconds(n))
        }
    }
}
```

The default implementation of this method returns `true`. Data formats
may override this to `false` to request a compact form for types that
support one. Note that modifying this method to change a format from
human-readable to compact or vice versa should be regarded as a breaking
change, as a value serialized in human-readable mode is not required to
deserialize from the same data in compact mode.

## serde::is_human_readable (function)

Determine whether `Serialize` implementations should serialize in
human-readable form.

Some types have a human-readable form that may be somewhat expensive to
construct, as well as a binary form that is compact and efficient.
Generally text-based formats like JSON and YAML will prefer to use the
human-readable one and binary formats like Postcard will prefer the
compact one.

```edition2021
# use std::fmt::{self, Display};
#
# struct Timestamp;
#
# impl Timestamp {
#     fn seconds_since_epoch(&self) -> u64 { unimplemented!() }
# }
#
# impl Display for Timestamp {
#     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         unimplemented!()
#     }
# }
#
use serde::{Serialize, Serializer};

impl Serialize for Timestamp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            // Serialize to a human-readable string "2015-05-15T17:01:00Z".
            self.to_string().serialize(serializer)
        } else {
            // Serialize to a compact binary representation.
            self.seconds_since_epoch().serialize(serializer)
        }
    }
}
```

The default implementation of this method returns `true`. Data formats
may override this to `false` to request a compact form for types that
support one. Note that modifying this method to change a format from
human-readable to compact or vice versa should be regarded as a breaking
change, as a value serialized in human-readable mode is not required to
deserialize from the same data in compact mode.

## serde::missing_field (function)

Raised when a `Deserialize` struct type expected to receive a required
field with a particular name but that field was not present in the
input.

## serde::new (function)

Construct a new `EnumAccessDeserializer<A>`.

## serde::new (function)

Construct a new `MapAccessDeserializer<A>`.

## serde::new (function)

Construct a new `MapDeserializer<I, E>`.

## serde::new (function)

Construct a new `SeqAccessDeserializer<A>`.

## serde::new (function)

Construct a new `SeqDeserializer<I, E>`.

## serde::new (function)

Create a new borrowed deserializer from the given borrowed bytes.

## serde::new (function)

Create a new borrowed deserializer from the given string.

## serde::new (function)

Create a new deserializer from the given bytes.

## serde::newtype_variant (function)

Called when deserializing a variant with a single value.

This method exists as a convenience for `Deserialize` implementations.
`VariantAccess` implementations should not override the default
behavior.

## serde::newtype_variant_seed (function)

Called when deserializing a variant with a single value.

`Deserialize` implementations should typically use
`VariantAccess::newtype_variant` instead.

If the data contains a different type of variant, the following
`invalid_type` error should be constructed:

```edition2021
# use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
#
# struct X;
#
# impl<'de> VariantAccess<'de> for X {
#     type Error = value::Error;
#
#     fn unit_variant(self) -> Result<(), Self::Error> {
#         unimplemented!()
#     }
#
fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error>
where
    T: DeserializeSeed<'de>,
{
    // What the data actually contained; suppose it is a unit variant.
    let unexp = Unexpected::UnitVariant;
    Err(de::Error::invalid_type(unexp, &"newtype variant"))
}
#
#     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
#
#     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
# }
```

## serde::next_element (function)

This returns `Ok(Some(value))` for the next value in the sequence, or
`Ok(None)` if there are no more remaining items.

This method exists as a convenience for `Deserialize` implementations.
`SeqAccess` implementations should not override the default behavior.

## serde::next_element_seed (function)

This returns `Ok(Some(value))` for the next value in the sequence, or
`Ok(None)` if there are no more remaining items.

`Deserialize` implementations should typically use
`SeqAccess::next_element` instead.

## serde::next_entry (function)

This returns `Ok(Some((key, value)))` for the next (key-value) pair in
the map, or `Ok(None)` if there are no more remaining items.

This method exists as a convenience for `Deserialize` implementations.
`MapAccess` implementations should not override the default behavior.

## serde::next_entry_seed (function)

This returns `Ok(Some((key, value)))` for the next (key-value) pair in
the map, or `Ok(None)` if there are no more remaining items.

`MapAccess` implementations should override the default behavior if a
more efficient implementation is possible.

`Deserialize` implementations should typically use
`MapAccess::next_entry` instead.

## serde::next_key (function)

This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
if there are no more remaining entries.

This method exists as a convenience for `Deserialize` implementations.
`MapAccess` implementations should not override the default behavior.

## serde::next_key_seed (function)

This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)`
if there are no more remaining entries.

`Deserialize` implementations should typically use
`MapAccess::next_key` or `MapAccess::next_entry` instead.

## serde::next_value (function)

This returns a `Ok(value)` for the next value in the map.

This method exists as a convenience for `Deserialize` implementations.
`MapAccess` implementations should not override the default behavior.

### serde::next_value (function) › Panics

Calling `next_value` before `next_key` is incorrect and is allowed to
panic or return bogus results.

## serde::next_value_seed (function)

This returns a `Ok(value)` for the next value in the map.

`Deserialize` implementations should typically use
`MapAccess::next_value` instead.

### serde::next_value_seed (function) › Panics

Calling `next_value_seed` before `next_key_seed` is incorrect and is
allowed to panic or return bogus results.

## serde::ser::Error (trait)

Trait used by `Serialize` implementations to generically construct
errors belonging to the `Serializer` against which they are
currently running.

### serde::ser::Error (trait) › Example implementation

The [example data format] presented on the website shows an error
type appropriate for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::Serialize (trait)

A **data structure** that can be serialized into any data format supported
by Serde.

Serde provides `Serialize` implementations for many Rust primitive and
standard library types. The complete list is [here][crate::ser]. All of
these can be serialized using Serde out of the box.

Additionally, Serde provides a procedural macro called [`serde_derive`] to
automatically generate `Serialize` implementations for structs and enums in
your program. See the [derive section of the manual] for how to use this.

In rare cases it may be necessary to implement `Serialize` manually for some
type in your program. See the [Implementing `Serialize`] section of the
manual for more about this.

Third-party crates may provide `Serialize` implementations for types that
they expose. For example the [`linked-hash-map`] crate provides a
[`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate
provides an implementation of `Serialize` for it.

[Implementing `Serialize`]: https://serde.rs/impl-serialize.html
[`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html
[`linked-hash-map`]: https://crates.io/crates/linked-hash-map
[`serde_derive`]: https://crates.io/crates/serde_derive
[derive section of the manual]: https://serde.rs/derive.html

## serde::ser::SerializeMap (trait)

Returned from `Serializer::serialize_map`.

### serde::ser::SerializeMap (trait) › Example use

```edition2021
# use std::marker::PhantomData;
#
# struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
#
# impl<K, V> HashMap<K, V> {
#     fn len(&self) -> usize {
#         unimplemented!()
#     }
# }
#
# impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
#     type Item = (&'a K, &'a V);
#     type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
#
#     fn into_iter(self) -> Self::IntoIter {
#         unimplemented!()
#     }
# }
#
use serde::ser::{Serialize, SerializeMap, Serializer};

impl<K, V> Serialize for HashMap<K, V>
where
    K: Serialize,
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.len()))?;
        for (k, v) in self {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}
```

### serde::ser::SerializeMap (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeMap` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeMap::serialize_key (function)

Serialize a map key.

If possible, `Serialize` implementations are encouraged to use
`serialize_entry` instead as it may be implemented more efficiently in
some formats compared to a pair of calls to `serialize_key` and
`serialize_value`.

## serde::ser::SerializeMap::serialize_value (function)

Serialize a map value.

### serde::ser::SerializeMap::serialize_value (function) › Panics

Calling `serialize_value` before `serialize_key` is incorrect and is
allowed to panic or produce bogus results.

## serde::ser::SerializeSeq (trait)

Returned from `Serializer::serialize_seq`.

### serde::ser::SerializeSeq (trait) › Example use

```edition2021
# use std::marker::PhantomData;
#
# struct Vec<T>(PhantomData<T>);
#
# impl<T> Vec<T> {
#     fn len(&self) -> usize {
#         unimplemented!()
#     }
# }
#
# impl<'a, T> IntoIterator for &'a Vec<T> {
#     type Item = &'a T;
#     type IntoIter = Box<dyn Iterator<Item = &'a T>>;
#     fn into_iter(self) -> Self::IntoIter {
#         unimplemented!()
#     }
# }
#
use serde::ser::{Serialize, SerializeSeq, Serializer};

impl<T> Serialize for Vec<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for element in self {
            seq.serialize_element(element)?;
        }
        seq.end()
    }
}
```

### serde::ser::SerializeSeq (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeSeq` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeStruct (trait)

Returned from `Serializer::serialize_struct`.

### serde::ser::SerializeStruct (trait) › Example use

```edition2021
use serde::ser::{Serialize, SerializeStruct, Serializer};

struct Rgb {
    r: u8,
    g: u8,
    b: u8,
}

impl Serialize for Rgb {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut rgb = serializer.serialize_struct("Rgb", 3)?;
        rgb.serialize_field("r", &self.r)?;
        rgb.serialize_field("g", &self.g)?;
        rgb.serialize_field("b", &self.b)?;
        rgb.end()
    }
}
```

### serde::ser::SerializeStruct (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeStruct` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeStruct::skip_field (function)

Indicate that a struct field has been skipped.

The default implementation does nothing.

## serde::ser::SerializeStructVariant (trait)

Returned from `Serializer::serialize_struct_variant`.

### serde::ser::SerializeStructVariant (trait) › Example use

```edition2021
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()
            }
        }
    }
}
```

### serde::ser::SerializeStructVariant (trait) › Example implementation

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

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeStructVariant::skip_field (function)

Indicate that a struct variant field has been skipped.

The default implementation does nothing.

## serde::ser::SerializeTuple (trait)

Returned from `Serializer::serialize_tuple`.

### serde::ser::SerializeTuple (trait) › Example use

```edition2021
use serde::ser::{Serialize, SerializeTuple, Serializer};

# mod fool {
#     trait Serialize {}
impl<A, B, C> Serialize for (A, B, C)
#     {}
# }
#
# struct Tuple3<A, B, C>(A, B, C);
#
# impl<A, B, C> Serialize for Tuple3<A, B, C>
where
    A: Serialize,
    B: Serialize,
    C: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut tup = serializer.serialize_tuple(3)?;
        tup.serialize_element(&self.0)?;
        tup.serialize_element(&self.1)?;
        tup.serialize_element(&self.2)?;
        tup.end()
    }
}
```

```edition2021
# use std::marker::PhantomData;
#
# struct Array<T>(PhantomData<T>);
#
# impl<T> Array<T> {
#     fn len(&self) -> usize {
#         unimplemented!()
#     }
# }
#
# impl<'a, T> IntoIterator for &'a Array<T> {
#     type Item = &'a T;
#     type IntoIter = Box<dyn Iterator<Item = &'a T>>;
#     fn into_iter(self) -> Self::IntoIter {
#         unimplemented!()
#     }
# }
#
use serde::ser::{Serialize, SerializeTuple, Serializer};

# mod fool {
#     trait Serialize {}
impl<T> Serialize for [T; 16]
#     {}
# }
#
# impl<T> Serialize for Array<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_tuple(16)?;
        for element in self {
            seq.serialize_element(element)?;
        }
        seq.end()
    }
}
```

### serde::ser::SerializeTuple (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeTuple` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeTupleStruct (trait)

Returned from `Serializer::serialize_tuple_struct`.

### serde::ser::SerializeTupleStruct (trait) › Example use

```edition2021
use serde::ser::{Serialize, SerializeTupleStruct, Serializer};

struct Rgb(u8, u8, u8);

impl Serialize for Rgb {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
        ts.serialize_field(&self.0)?;
        ts.serialize_field(&self.1)?;
        ts.serialize_field(&self.2)?;
        ts.end()
    }
}
```

### serde::ser::SerializeTupleStruct (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeTupleStruct` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::SerializeTupleVariant (trait)

Returned from `Serializer::serialize_tuple_variant`.

### serde::ser::SerializeTupleVariant (trait) › Example use

```edition2021
use serde::ser::{Serialize, SerializeTupleVariant, Serializer};

enum E {
    T(u8, u8),
    U(String, u32, u32),
}

impl Serialize for E {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            E::T(ref a, ref b) => {
                let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
                tv.serialize_field(a)?;
                tv.serialize_field(b)?;
                tv.end()
            }
            E::U(ref a, ref b, ref c) => {
                let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
                tv.serialize_field(a)?;
                tv.serialize_field(b)?;
                tv.serialize_field(c)?;
                tv.end()
            }
        }
    }
}
```

### serde::ser::SerializeTupleVariant (trait) › Example implementation

The [example data format] presented on the website demonstrates an
implementation of `SerializeTupleVariant` for a basic JSON data format.

[example data format]: https://serde.rs/data-format.html

## serde::ser::Serializer (trait)

A **data format** that can serialize any data structure supported by Serde.

The role of this trait is to define the serialization half of the [Serde
data model], which is a way to categorize every Rust data structure into one
of 29 possible types. Each method of the `Serializer` trait corresponds to
one of the types of the data model.

Implementations of `Serialize` map themselves into this data model by
invoking exactly one of the `Serializer` methods.

The types that make up the Serde data model are:

 - **14 primitive types**
   - bool
   - i8, i16, i32, i64, i128
   - u8, u16, u32, u64, u128
   - f32, f64
   - char
 - **string**
   - UTF-8 bytes with a length and no null terminator.
   - When serializing, all strings are handled equally. When deserializing,
     there are three flavors of strings: transient, owned, and borrowed.
 - **byte array** - \[u8\]
   - Similar to strings, during deserialization byte arrays can be
     transient, owned, or borrowed.
 - **option**
   - Either none or some value.
 - **unit**
   - The type of `()` in Rust. It represents an anonymous value containing
     no data.
 - **unit_struct**
   - For example `struct Unit` or `PhantomData<T>`. It represents a named
     value containing no data.
 - **unit_variant**
   - For example the `E::A` and `E::B` in `enum E { A, B }`.
 - **newtype_struct**
   - For example `struct Millimeters(u8)`.
 - **newtype_variant**
   - For example the `E::N` in `enum E { N(u8) }`.
 - **seq**
   - A variably sized heterogeneous sequence of values, for example
     `Vec<T>` or `HashSet<T>`. When serializing, the length may or may not
     be known before iterating through all the data. When deserializing,
     the length is determined by looking at the serialized data.
 - **tuple**
   - A statically sized heterogeneous sequence of values for which the
     length will be known at deserialization time without looking at the
     serialized data, for example `(u8,)` or `(String, u64, Vec<T>)` or
     `[u64; 10]`.
 - **tuple_struct**
   - A named tuple, for example `struct Rgb(u8, u8, u8)`.
 - **tuple_variant**
   - For example the `E::T` in `enum E { T(u8, u8) }`.
 - **map**
   - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`.
 - **struct**
   - A heterogeneous key-value pairing in which the keys are strings and
     will be known at deserialization time without looking at the
     serialized data, for example `struct S { r: u8, g: u8, b: u8 }`.
 - **struct_variant**
   - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`.

Many Serde serializers produce text or binary data as output, for example
JSON or Postcard. This is not a requirement of the `Serializer` trait, and
there are serializers that do not produce text or binary output. One example
is the `serde_json::value::Serializer` (distinct from the main `serde_json`
serializer) that produces a `serde_json::Value` data structure in memory as
output.

[Serde data model]: https://serde.rs/data-model.html

### serde::ser::Serializer (trait) › Example implementation

The [example data format] presented on the website contains example code for
a basic JSON `Serializer`.

[example data format]: https://serde.rs/data-format.html

## serde::ser::Serializer::serialize_str (function)

Serialize a `&str`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for str {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self)
    }
}
```

## serde::ser::impossible::Impossible (struct)

Helper type for implementing a `Serializer` that does not support
serializing one of the compound types.

This type cannot be instantiated, but implements every one of the traits
corresponding to the [`Serializer`] compound types: [`SerializeSeq`],
[`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`],
[`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`].

```edition2021
# use serde::ser::{Serializer, Impossible};
# use serde_core::__private::doc::Error;
#
# struct MySerializer;
#
impl Serializer for MySerializer {
    type Ok = ();
    type Error = Error;

    type SerializeSeq = Impossible<(), Error>;
    /* other associated types */

    /// This data format does not support serializing sequences.
    fn serialize_seq(self,
                     len: Option<usize>)
                     -> Result<Self::SerializeSeq, Error> {
        // Given Impossible cannot be instantiated, the only
        // thing we can do here is to return an error.
#         stringify! {
        Err(...)
#         };
#         unimplemented!()
    }

    /* other Serializer methods */
#     serde_core::__serialize_unimplemented! {
#         bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some
#         unit unit_struct unit_variant newtype_struct newtype_variant
#         tuple tuple_struct tuple_variant map struct struct_variant
#     }
}
```

[`Serializer`]: crate::Serializer
[`SerializeSeq`]: crate::ser::SerializeSeq
[`SerializeTuple`]: crate::ser::SerializeTuple
[`SerializeTupleStruct`]: crate::ser::SerializeTupleStruct
[`SerializeTupleVariant`]: crate::ser::SerializeTupleVariant
[`SerializeMap`]: crate::ser::SerializeMap
[`SerializeStruct`]: crate::ser::SerializeStruct
[`SerializeStructVariant`]: crate::ser::SerializeStructVariant

## serde::serialize (function)

Serialize this value into the given Serde serializer.

See the [Implementing `Serialize`] section of the manual for more
information about how to implement this method.

```edition2021
use serde::ser::{Serialize, SerializeStruct, Serializer};

struct Person {
    name: String,
    age: u8,
    phones: Vec<String>,
}

// This is what #[derive(Serialize)] would generate.
impl Serialize for Person {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut s = serializer.serialize_struct("Person", 3)?;
        s.serialize_field("name", &self.name)?;
        s.serialize_field("age", &self.age)?;
        s.serialize_field("phones", &self.phones)?;
        s.end()
    }
}
```

[Implementing `Serialize`]: https://serde.rs/impl-serialize.html

## serde::serialize_bool (function)

Serialize a `bool` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for bool {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_bool(*self)
    }
}
```

## serde::serialize_bytes (function)

Serialize a chunk of raw byte data.

Enables serializers to serialize byte slices more compactly or more
efficiently than other types of slices. If no efficient implementation
is available, a reasonable implementation would be to forward to
`serialize_seq`. If forwarded, the implementation looks usually just
like this:

```edition2021
# use serde::ser::{Serializer, SerializeSeq};
# use serde_core::__private::doc::Error;
#
# struct MySerializer;
#
# impl Serializer for MySerializer {
#     type Ok = ();
#     type Error = Error;
#
fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
    let mut seq = self.serialize_seq(Some(v.len()))?;
    for b in v {
        seq.serialize_element(b)?;
    }
    seq.end()
}
#
#     serde_core::__serialize_unimplemented! {
#         bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some
#         unit unit_struct unit_variant newtype_struct newtype_variant
#         seq tuple tuple_struct tuple_variant map struct struct_variant
#     }
# }
```

## serde::serialize_char (function)

Serialize a character.

If the format does not support characters, it is reasonable to serialize
it as a single element `str` or a `u32`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for char {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_char(*self)
    }
}
```

## serde::serialize_element (function)

Serialize a sequence element.

## serde::serialize_element (function)

Serialize a tuple element.

## serde::serialize_entry (function)

Serialize a map entry consisting of a key and a value.

Some [`Serialize`] types are not able to hold a key and value in memory
at the same time so `SerializeMap` implementations are required to
support [`serialize_key`] and [`serialize_value`] individually. The
`serialize_entry` method allows serializers to optimize for the case
where key and value are both available. [`Serialize`] implementations
are encouraged to use `serialize_entry` if possible.

The default implementation delegates to [`serialize_key`] and
[`serialize_value`]. This is appropriate for serializers that do not
care about performance or are not able to optimize `serialize_entry` any
better than this.

[`Serialize`]: crate::Serialize
[`serialize_key`]: Self::serialize_key
[`serialize_value`]: Self::serialize_value

## serde::serialize_f32 (function)

Serialize an `f32` value.

If the format does not differentiate between `f32` and `f64`, a
reasonable implementation would be to cast the value to `f64` and
forward to `serialize_f64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for f32 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_f32(*self)
    }
}
```

## serde::serialize_f64 (function)

Serialize an `f64` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for f64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_f64(*self)
    }
}
```

## serde::serialize_field (function)

Serialize a struct field.

## serde::serialize_field (function)

Serialize a struct variant field.

## serde::serialize_field (function)

Serialize a tuple struct field.

## serde::serialize_field (function)

Serialize a tuple variant field.

## serde::serialize_i128 (function)

Serialize an `i128` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for i128 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i128(*self)
    }
}
```

The default behavior unconditionally returns an error.

## serde::serialize_i16 (function)

Serialize an `i16` value.

If the format does not differentiate between `i16` and `i64`, a
reasonable implementation would be to cast the value to `i64` and
forward to `serialize_i64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for i16 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i16(*self)
    }
}
```

## serde::serialize_i32 (function)

Serialize an `i32` value.

If the format does not differentiate between `i32` and `i64`, a
reasonable implementation would be to cast the value to `i64` and
forward to `serialize_i64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for i32 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i32(*self)
    }
}
```

## serde::serialize_i64 (function)

Serialize an `i64` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for i64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i64(*self)
    }
}
```

## serde::serialize_i8 (function)

Serialize an `i8` value.

If the format does not differentiate between `i8` and `i64`, a
reasonable implementation would be to cast the value to `i64` and
forward to `serialize_i64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for i8 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_i8(*self)
    }
}
```

## serde::serialize_map (function)

Begin to serialize a map. This call must be followed by zero or more
calls to `serialize_key` and `serialize_value`, then a call to `end`.

The argument is the number of elements in the map, which may or may not
be computable before the map is iterated. Some serializers only support
maps whose length is known up front.

```edition2021
# use std::marker::PhantomData;
#
# struct HashMap<K, V>(PhantomData<K>, PhantomData<V>);
#
# impl<K, V> HashMap<K, V> {
#     fn len(&self) -> usize {
#         unimplemented!()
#     }
# }
#
# impl<'a, K, V> IntoIterator for &'a HashMap<K, V> {
#     type Item = (&'a K, &'a V);
#     type IntoIter = Box<dyn Iterator<Item = (&'a K, &'a V)>>;
#
#     fn into_iter(self) -> Self::IntoIter {
#         unimplemented!()
#     }
# }
#
use serde::ser::{Serialize, SerializeMap, Serializer};

impl<K, V> Serialize for HashMap<K, V>
where
    K: Serialize,
    V: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.len()))?;
        for (k, v) in self {
            map.serialize_entry(k, v)?;
        }
        map.end()
    }
}
```

## serde::serialize_newtype_struct (function)

Serialize a newtype struct like `struct Millimeters(u8)`.

Serializers are encouraged to treat newtype structs as insignificant
wrappers around the data they contain. A reasonable implementation would
be to forward to `value.serialize(self)`.

```edition2021
use serde::{Serialize, Serializer};

struct Millimeters(u8);

impl Serialize for Millimeters {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_newtype_struct("Millimeters", &self.0)
    }
}
```

## serde::serialize_newtype_variant (function)

Serialize a newtype variant like `E::N` in `enum E { N(u8) }`.

The `name` is the name of the enum, the `variant_index` is the index of
this variant within the enum, and the `variant` is the name of the
variant. The `value` is the data contained within this newtype variant.

```edition2021
use serde::{Serialize, Serializer};

enum E {
    M(String),
    N(u8),
}

impl Serialize for E {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s),
            E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n),
        }
    }
}
```

## serde::serialize_none (function)

Serialize a [`None`] value.

```edition2021
# use serde::{Serialize, Serializer};
#
# enum Option<T> {
#     Some(T),
#     None,
# }
#
# use self::Option::{Some, None};
#
impl<T> Serialize for Option<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            Some(ref value) => serializer.serialize_some(value),
            None => serializer.serialize_none(),
        }
    }
}
#
# fn main() {}
```

[`None`]: core::option::Option::None

## serde::serialize_seq (function)

Begin to serialize a variably sized sequence. This call must be
followed by zero or more calls to `serialize_element`, then a call to
`end`.

The argument is the number of elements in the sequence, which may or may
not be computable before the sequence is iterated. Some serializers only
support sequences whose length is known up front.

```edition2021
# use std::marker::PhantomData;
#
# struct Vec<T>(PhantomData<T>);
#
# impl<T> Vec<T> {
#     fn len(&self) -> usize {
#         unimplemented!()
#     }
# }
#
# impl<'a, T> IntoIterator for &'a Vec<T> {
#     type Item = &'a T;
#     type IntoIter = Box<dyn Iterator<Item = &'a T>>;
#
#     fn into_iter(self) -> Self::IntoIter {
#         unimplemented!()
#     }
# }
#
use serde::ser::{Serialize, SerializeSeq, Serializer};

impl<T> Serialize for Vec<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for element in self {
            seq.serialize_element(element)?;
        }
        seq.end()
    }
}
```

## serde::serialize_some (function)

Serialize a [`Some(T)`] value.

```edition2021
# use serde::{Serialize, Serializer};
#
# enum Option<T> {
#     Some(T),
#     None,
# }
#
# use self::Option::{Some, None};
#
impl<T> Serialize for Option<T>
where
    T: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            Some(ref value) => serializer.serialize_some(value),
            None => serializer.serialize_none(),
        }
    }
}
#
# fn main() {}
```

[`Some(T)`]: core::option::Option::Some

## serde::serialize_struct (function)

Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`.
This call must be followed by zero or more calls to `serialize_field`,
then a call to `end`.

The `name` is the name of the struct and the `len` is the number of
data fields that will be serialized. `len` does not include fields
which are skipped with [`SerializeStruct::skip_field`].

```edition2021
use serde::ser::{Serialize, SerializeStruct, Serializer};

struct Rgb {
    r: u8,
    g: u8,
    b: u8,
}

impl Serialize for Rgb {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut rgb = serializer.serialize_struct("Rgb", 3)?;
        rgb.serialize_field("r", &self.r)?;
        rgb.serialize_field("g", &self.g)?;
        rgb.serialize_field("b", &self.b)?;
        rgb.end()
    }
}
```

## serde::serialize_struct_variant (function)

Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8,
g: u8, b: u8 } }`. This call must be followed by zero or more calls to
`serialize_field`, then a call to `end`.

The `name` is the name of the enum, the `variant_index` is the index of
this variant within the enum, the `variant` is the name of the variant,
and the `len` is the number of data fields that will be serialized.
`len` does not include fields which are skipped with
[`SerializeStructVariant::skip_field`].

```edition2021
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()
            }
        }
    }
}
```

## serde::serialize_tuple (function)

Begin to serialize a statically sized sequence whose length will be
known at deserialization time without looking at the serialized data.
This call must be followed by zero or more calls to `serialize_element`,
then a call to `end`.

```edition2021
use serde::ser::{Serialize, SerializeTuple, Serializer};

# mod fool {
#     trait Serialize {}
impl<A, B, C> Serialize for (A, B, C)
#     {}
# }
#
# struct Tuple3<A, B, C>(A, B, C);
#
# impl<A, B, C> Serialize for Tuple3<A, B, C>
where
    A: Serialize,
    B: Serialize,
    C: Serialize,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut tup = serializer.serialize_tuple(3)?;
        tup.serialize_element(&self.0)?;
        tup.serialize_element(&self.1)?;
        tup.serialize_element(&self.2)?;
        tup.end()
    }
}
```

```edition2021
use serde::ser::{Serialize, SerializeTuple, Serializer};

const VRAM_SIZE: usize = 386;
struct Vram([u16; VRAM_SIZE]);

impl Serialize for Vram {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_tuple(VRAM_SIZE)?;
        for element in &self.0[..] {
            seq.serialize_element(element)?;
        }
        seq.end()
    }
}
```

## serde::serialize_tuple_struct (function)

Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This
call must be followed by zero or more calls to `serialize_field`, then a
call to `end`.

The `name` is the name of the tuple struct and the `len` is the number
of data fields that will be serialized.

```edition2021
use serde::ser::{Serialize, SerializeTupleStruct, Serializer};

struct Rgb(u8, u8, u8);

impl Serialize for Rgb {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?;
        ts.serialize_field(&self.0)?;
        ts.serialize_field(&self.1)?;
        ts.serialize_field(&self.2)?;
        ts.end()
    }
}
```

## serde::serialize_tuple_variant (function)

Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8)
}`. This call must be followed by zero or more calls to
`serialize_field`, then a call to `end`.

The `name` is the name of the enum, the `variant_index` is the index of
this variant within the enum, the `variant` is the name of the variant,
and the `len` is the number of data fields that will be serialized.

```edition2021
use serde::ser::{Serialize, SerializeTupleVariant, Serializer};

enum E {
    T(u8, u8),
    U(String, u32, u32),
}

impl Serialize for E {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            E::T(ref a, ref b) => {
                let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?;
                tv.serialize_field(a)?;
                tv.serialize_field(b)?;
                tv.end()
            }
            E::U(ref a, ref b, ref c) => {
                let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?;
                tv.serialize_field(a)?;
                tv.serialize_field(b)?;
                tv.serialize_field(c)?;
                tv.end()
            }
        }
    }
}
```

## serde::serialize_u128 (function)

Serialize a `u128` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for u128 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u128(*self)
    }
}
```

The default behavior unconditionally returns an error.

## serde::serialize_u16 (function)

Serialize a `u16` value.

If the format does not differentiate between `u16` and `u64`, a
reasonable implementation would be to cast the value to `u64` and
forward to `serialize_u64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for u16 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u16(*self)
    }
}
```

## serde::serialize_u32 (function)

Serialize a `u32` value.

If the format does not differentiate between `u32` and `u64`, a
reasonable implementation would be to cast the value to `u64` and
forward to `serialize_u64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for u32 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u32(*self)
    }
}
```

## serde::serialize_u64 (function)

Serialize a `u64` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for u64 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u64(*self)
    }
}
```

## serde::serialize_u8 (function)

Serialize a `u8` value.

If the format does not differentiate between `u8` and `u64`, a
reasonable implementation would be to cast the value to `u64` and
forward to `serialize_u64`.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for u8 {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_u8(*self)
    }
}
```

## serde::serialize_unit (function)

Serialize a `()` value.

```edition2021
# use serde::Serializer;
#
# serde_core::__private_serialize!();
#
impl Serialize for () {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_unit()
    }
}
```

## serde::serialize_unit_struct (function)

Serialize a unit struct like `struct Unit` or `PhantomData<T>`.

A reasonable implementation would be to forward to `serialize_unit`.

```edition2021
use serde::{Serialize, Serializer};

struct Nothing;

impl Serialize for Nothing {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_unit_struct("Nothing")
    }
}
```

## serde::serialize_unit_variant (function)

Serialize a unit variant like `E::A` in `enum E { A, B }`.

The `name` is the name of the enum, the `variant_index` is the index of
this variant within the enum, and the `variant` is the name of the
variant.

```edition2021
use serde::{Serialize, Serializer};

enum E {
    A,
    B,
}

impl Serialize for E {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match *self {
            E::A => serializer.serialize_unit_variant("E", 0, "A"),
            E::B => serializer.serialize_unit_variant("E", 1, "B"),
        }
    }
}
```

## serde::size_hint (function)

Returns the number of elements remaining in the sequence, if known.

## serde::size_hint (function)

Returns the number of entries remaining in the map, if known.

## serde::struct_variant (function)

Called when deserializing a struct-like variant.

The `fields` are the names of the fields of the struct variant.

If the data contains a different type of variant, the following
`invalid_type` error should be constructed:

```edition2021
# use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
#
# struct X;
#
# impl<'de> VariantAccess<'de> for X {
#     type Error = value::Error;
#
#     fn unit_variant(self) -> Result<(), Self::Error> {
#         unimplemented!()
#     }
#
#     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
#     where
#         T: DeserializeSeed<'de>,
#     { unimplemented!() }
#
#     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
#
fn struct_variant<V>(
    self,
    _fields: &'static [&'static str],
    _visitor: V,
) -> Result<V::Value, Self::Error>
where
    V: Visitor<'de>,
{
    // What the data actually contained; suppose it is a unit variant.
    let unexp = Unexpected::UnitVariant;
    Err(de::Error::invalid_type(unexp, &"struct variant"))
}
# }
```

## serde::tuple_variant (function)

Called when deserializing a tuple-like variant.

The `len` is the number of fields expected in the tuple variant.

If the data contains a different type of variant, the following
`invalid_type` error should be constructed:

```edition2021
# use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
#
# struct X;
#
# impl<'de> VariantAccess<'de> for X {
#     type Error = value::Error;
#
#     fn unit_variant(self) -> Result<(), Self::Error> {
#         unimplemented!()
#     }
#
#     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
#     where
#         T: DeserializeSeed<'de>,
#     { unimplemented!() }
#
fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error>
where
    V: Visitor<'de>,
{
    // What the data actually contained; suppose it is a unit variant.
    let unexp = Unexpected::UnitVariant;
    Err(de::Error::invalid_type(unexp, &"tuple variant"))
}
#
#     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
# }
```

## serde::unit_variant (function)

Called when deserializing a variant with no values.

If the data contains a different type of variant, the following
`invalid_type` error should be constructed:

```edition2021
# use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected};
#
# struct X;
#
# impl<'de> VariantAccess<'de> for X {
#     type Error = value::Error;
#
fn unit_variant(self) -> Result<(), Self::Error> {
    // What the data actually contained; suppose it is a tuple variant.
    let unexp = Unexpected::TupleVariant;
    Err(de::Error::invalid_type(unexp, &"unit variant"))
}
#
#     fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error>
#     where
#         T: DeserializeSeed<'de>,
#     { unimplemented!() }
#
#     fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
#
#     fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error>
#     where
#         V: Visitor<'de>,
#     { unimplemented!() }
# }
```

## serde::unknown_field (function)

Raised when a `Deserialize` struct type received a field with an
unrecognized name.

## serde::unknown_variant (function)

Raised when a `Deserialize` enum type received a variant with an
unrecognized name.

## serde::variant (function)

`variant` is called to identify which variant to deserialize.

This method exists as a convenience for `Deserialize` implementations.
`EnumAccess` implementations should not override the default behavior.

## serde::variant_seed (function)

`variant` is called to identify which variant to deserialize.

`Deserialize` implementations should typically use `EnumAccess::variant`
instead.

## serde::visit_bool (function)

The input contains a boolean.

The default implementation fails with a type error.

## serde::visit_borrowed_str (function)

The input contains a string that lives at least as long as the
`Deserializer`.

This enables zero-copy deserialization of strings in some formats. For
example JSON input containing the JSON string `"borrowed"` can be
deserialized with zero copying into a `&'a str` as long as the input
data outlives `'a`.

The default implementation forwards to `visit_str`.

## serde::visit_byte_buf (function)

The input contains a byte array and ownership of the byte array is being
given to the `Visitor`.

This method allows the `Visitor` to avoid a copy by taking ownership of
a byte buffer created by the `Deserializer`. `Deserialize`
implementations that benefit from taking ownership of `Vec<u8>` data
should indicate that to the deserializer by using
`Deserializer::deserialize_byte_buf` rather than
`Deserializer::deserialize_bytes`, although not every deserializer will
honor such a request.

It is never correct to implement `visit_byte_buf` without implementing
`visit_bytes`. Implement neither, both, or just `visit_bytes`.

The default implementation forwards to `visit_bytes` and then drops the
`Vec<u8>`.

## serde::visit_char (function)

The input contains a `char`.

The default implementation forwards to [`visit_str`] as a one-character
string.

[`visit_str`]: #method.visit_str

## serde::visit_enum (function)

The input contains an enum.

The default implementation fails with a type error.

## serde::visit_f32 (function)

The input contains an `f32`.

The default implementation forwards to [`visit_f64`].

[`visit_f64`]: #method.visit_f64

## serde::visit_f64 (function)

The input contains an `f64`.

The default implementation fails with a type error.

## serde::visit_i128 (function)

The input contains a `i128`.

The default implementation fails with a type error.

## serde::visit_i16 (function)

The input contains an `i16`.

The default implementation forwards to [`visit_i64`].

[`visit_i64`]: #method.visit_i64

## serde::visit_i32 (function)

The input contains an `i32`.

The default implementation forwards to [`visit_i64`].

[`visit_i64`]: #method.visit_i64

## serde::visit_i64 (function)

The input contains an `i64`.

The default implementation fails with a type error.

## serde::visit_i8 (function)

The input contains an `i8`.

The default implementation forwards to [`visit_i64`].

[`visit_i64`]: #method.visit_i64

## serde::visit_map (function)

The input contains a key-value map.

The default implementation fails with a type error.

## serde::visit_newtype_struct (function)

The input contains a newtype struct.

The content of the newtype struct may be read from the given
`Deserializer`.

The default implementation fails with a type error.

## serde::visit_none (function)

The input contains an optional that is absent.

The default implementation fails with a type error.

## serde::visit_seq (function)

The input contains a sequence of elements.

The default implementation fails with a type error.

## serde::visit_some (function)

The input contains an optional that is present.

The default implementation fails with a type error.

## serde::visit_str (function)

The input contains a string. The lifetime of the string is ephemeral and
it may be destroyed after this method returns.

This method allows the `Deserializer` to avoid a copy by retaining
ownership of any buffered data. `Deserialize` implementations that do
not benefit from taking ownership of `String` data should indicate that
to the deserializer by using `Deserializer::deserialize_str` rather than
`Deserializer::deserialize_string`.

It is never correct to implement `visit_string` without implementing
`visit_str`. Implement neither, both, or just `visit_str`.

## serde::visit_string (function)

The input contains a string and ownership of the string is being given
to the `Visitor`.

This method allows the `Visitor` to avoid a copy by taking ownership of
a string created by the `Deserializer`. `Deserialize` implementations
that benefit from taking ownership of `String` data should indicate that
to the deserializer by using `Deserializer::deserialize_string` rather
than `Deserializer::deserialize_str`, although not every deserializer
will honor such a request.

It is never correct to implement `visit_string` without implementing
`visit_str`. Implement neither, both, or just `visit_str`.

The default implementation forwards to `visit_str` and then drops the
`String`.

## serde::visit_u128 (function)

The input contains a `u128`.

The default implementation fails with a type error.

## serde::visit_u16 (function)

The input contains a `u16`.

The default implementation forwards to [`visit_u64`].

[`visit_u64`]: #method.visit_u64

## serde::visit_u32 (function)

The input contains a `u32`.

The default implementation forwards to [`visit_u64`].

[`visit_u64`]: #method.visit_u64

## serde::visit_u64 (function)

The input contains a `u64`.

The default implementation fails with a type error.

## serde::visit_u8 (function)

The input contains a `u8`.

The default implementation forwards to [`visit_u64`].

[`visit_u64`]: #method.visit_u64

## serde::visit_unit (function)

The input contains a unit `()`.

The default implementation fails with a type error.

