The extent of traits in Rust
Traits are a major and integral feature of Rust. Instead of hard-coding basic behaviour of types into the language itself, it uses the syntax to call trait methods in the vast majority of cases. Many of them also rely on generics, but as I'm not going into detail on any of the traits for now, just take a few for example:
- Adding two values is implemented in the Addtrait, subtracting in theSubtrait, and so on.
- Comparing two values for equality is implemented in the PartialEqandEqtraits.
- Checking the ordering (greater-than etc) is done in the PartialOrdandOrdtraits.
- The copy-constructor is implemented through the Clonetrait.
- Printing is done with the DisplayandDebugtraits. Additional formatting has extra traits, such asUpperHex.
- Converting between types uses the FromandIntotraits.
- Automatic dereferencing to inner types uses the DerefandDerefMuttraits.
This not only simplifies the language and puts some separation between syntax and functionality, but also allows you to integrate your custom types incredibly well with built in types, since the written code calls the exact same interfaces on them.
Additionally to explicit traits like this, there are also so-called auto traits that don't add functionality, but tell the language how to handle a type. Some more examples:
- Sizedtells the language that the size of the type is known at compile time.
- Sendnotes a type that is safe to send to another thread,- Syncmeans it's safe to share a reference to the object with other threads.
- Unpintypes can change their position in memory even after being pinned.
- The Copytrait doesn't implement anything itself, but signals that a type doesn't need a deep copy for cloning.