[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…
In the second part of the Advanced Rust article on API design principles, the focus shifts to implementing several traits: Clone, Default, PartialEq, PartialOrd, Hash, Eq, and Ord.
Implementing the Clone trait enables an implementer to create an explicit deep copy of the type using the clone method, as opposed to the shallow copy provided by the Copy trait. The example in the article demonstrates this by defining a Person struct with fields for name and age, then using Clone to create a copy of a person instance in main. The output shows both instances are identical, confirming a deep copy has occurred.
The Default trait is recommended for implementing in cases where a type can define a default value. The default() method returns that default instance. An example is given with a Point struct having x and y coordinates, showcasing how the default() method produces a point at (0, 0).
Three traits - PartialEq, PartialOrd, Hash, Eq, and Ord - are recommended to be implemented together when possible. PartialEq allows for partial equality comparisons with == and != operators. PartialOrd enables partial ordering comparisons with <, >, <=, and >= operators. Eq requires PartialEq to be implemented and enforces reflexivity (a == a). Ord requires PartialOrd and provides total ordering for sorting purposes, such as with BTreeMap and BTreeSet.
The article provides a concrete example using a Person struct implementing all six traits. A BTreeMap is used to store Person instances as keys, along with their ages as values. Values are inserted for three Person instances, then iterated over to print out each person's name and age.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
