expression

Manual Serialize implementation

Choose a wire representation for a domain type when derive is not enough. A numeric wrapper can serialize as its inner number without exposing its internal structure. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 42 Common mistake: Hardcoding JSON text in a format-independent serializer.

Formal Syntax & Structure

rust syntaxrust
impl serde::Serialize for T

Working Example

Example Snippetrust
fn main() {    struct Pages(u32);    impl serde::Serialize for Pages {        fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {            s.serialize_u32(self.0)        }    }    println!("{}", serde_json::to_string(&Pages(42)).unwrap());}
Rust Reference