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
Add
trait, subtracting in theSub
trait, and so on. - Comparing two values for equality is implemented in the
PartialEq
andEq
traits. - Checking the ordering (greater-than etc) is done in the
PartialOrd
andOrd
traits. - The copy-constructor is implemented through the
Clone
trait. - Printing is done with the
Display
andDebug
traits. Additional formatting has extra traits, such asUpperHex
. - Converting between types uses the
From
andInto
traits. - Automatic dereferencing to inner types uses the
Deref
andDerefMut
traits.
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:
Sized
tells the language that the size of the type is known at compile time.Send
notes a type that is safe to send to another thread,Sync
means it's safe to share a reference to the object with other threads.Unpin
types can change their position in memory even after being pinned.- The
Copy
trait doesn't implement anything itself, but signals that a type doesn't need a deep copy for cloning.