[Advanced Rust] 2.3. API Design Principles of Unsurprising Pt.3 - Implementing serde Serialize and Deserialize Traits, and Why…
Full title: [Advanced Rust] 2.3. API Design Principles of Unsurprising Pt.3 - Implementing serde Serialize and Deserialize Traits, and Why Copy Is Not Recommended 2.3.1. It Is Recommended to Implement Serialize and Deserialize in serde Serde is the core Rust library for serialization and deserialization : Serialization : converts a Rust struct or enum into a string or binary representation such as JSON or YAML Deserialization : parses a string or binary representation such as JSON or YAML back into a Rust struct or enum Serialize and Deserialize are both traits from the serde crate. Serialize Trait The Serialize trait allows a type to be converted into a serializable data format such as JSON, YAML, or TOML. Its main methods include: serialize_bool serialize_i32 serialize_str serialize_struct These are methods on the Serializer (and related) traits that a Serialize implementation calls; the Serialize trait itself only requires serialize . Its definition is: pub trait Serialize { fn serialize < S > ( & self , serializer : S ) -> Result < S :: Ok , S :: Error > where S : Serializer ; } Here is an example showing how to implement Serialize manually: use serde :: ser ::{ Serialize , SerializeStruct , Serializer }; struct Point { x : i32 , y : i32 , } impl Serialize for Point { fn serialize < S > ( & self , serializer : S ) -> Result < S :: Ok , S :: Error > where S : Serializer , { let mut state = serializer .serialize_struct ( "Point" , 2 ) ? ; state .serialize_field ( "x" , & self .x ) ? ; state .serialize_field ( "y" , & self .y ) ? ; state .end () } } serializer.serialize_struct("Point", 2)? creates a struct serializer state, and 2 is the number of fields state.serialize_field("x", &self.x)? serializes the struct fields one by one state.end() finishes serialization Deserialize Trait The Deserialize trait allows Rust types to be parsed from various data formats. Its main methods include: deserialize_bool deserialize_i32 deserialize_string deserialize_struct These are