Built-in traits and operator overloading
The Rust standard library is packed with traits, which are used all over the place. For example, there are traits for which the compiler is capable of providing a basic implementation with a #[derive]
attribute, as we saw in the section on Traits:
- Comparing instances: The
Eq
andPartialEq
trait - Ordering instances: The
Ord
andPartialOrd
trait - Creating an empty instance: The
Default
trait - To create a zero instance of a numeric data type: The
Zero
trait
The next chapter shows an example of how to implement the following three traits:
- Formatting a value using {
:?
}: TheDebug
trait, defining anfmt
method - Copy an instance: The
Copy
trait - Create a duplicate instance: The
Clone
trait - Computing a hash: The
Hash
trait - Adding instances: The
Add
trait, defining anadd
method. The+
operator is just a nice way to useadd: n + m
is the same asn.add(m)
. So if we implement theAdd
trait, we can use the+
operator, this is called operator overloading.- The
Add
trait has the...
- The