[Advanced Rust] 2.2. API Design Principles of Unsurprising Pt.2 - Implementing Clone, Default, PartialEq, PartialOrd, Hash, Eq…
Full title: [Advanced Rust] 2.2. API Design Principles of Unsurprising Pt.2 - Implementing Clone, Default, PartialEq, PartialOrd, Hash, Eq, and Ord 2.2.1. It Is Recommended to Implement the Clone Trait and the Default Trait Clone Trait The Clone trait in Rust allows an implementer to explicitly create a deep copy of itself through the clone method, as opposed to the by-value copy provided by the Copy trait. Example: #[derive(Debug, Clone)] struct Person { name : String , age : u32 , } impl Person { fn new ( name : String , age : u32 ) -> Self { Self { name , age } } } fn main () { let person1 = Person :: new ( "John" .to_owned (), 25 ); let person2 = person1 .clone (); println! ( "{:?}" , person1 ); println! ( "{:?}" , person2 ); } The Person struct implements the Clone trait In main , person2 clones the data from person1 because it implements Clone Output: Person { name: "John", age: 25 } Person { name: "John", age: 25 } Default Trait The Default trait in Rust allows a type to define a default value and return that default instance through the default() method. Example: #[derive(Default)] struct Point { x : i32 , y : i32 , } fn main () { let p = Point :: default (); println! ( "Point is at ({}, {})" , p .x , p .y ); } Output: Point is at (0, 0) 2.2.2. It Is Recommended to Implement the PartialEq , PartialOrd , Hash , Eq , and Ord Traits PartialEq Trait PartialEq provides support for the == and != operators, allowing custom types to participate in partial equality comparisons. Example: #[derive(Debug, PartialEq)] struct Point { x : i32 , y : i32 , } fn main () { let point1 : Point = Point { x : 1 , y : 2 }; let point2 : Point = Point { x : 1 , y : 2 }; let point3 : Point = Point { x : 3 , y : 4 }; println! ( "point1 == point2: {}" , point1 == point2 ); println! ( "point1 == point3: {}" , point1 == point3 ); } By implementing PartialEq , we can compare whether two structs are equal Output: point1 == point2: true point1 == point3: false PartialOrd , Eq , and Ord Trait