17
Traits
Traits are abstract types that describe a behavior, which can consist of multiple functions. Traits are implemented by concrete types. Each implementation of a trait is a specialization for that type.
Traits create relationships between types. For example, the GasCar, ElectricCar, and HybridCar types could implement a Car trait. Each of them is a kind of Car. As such, they share a common interface and behavior, such as start, brake, accelerate, and turn functions. For these reasons, types that implement the same trait are related and interchangeable.
Types can implement more than one trait. An Amphibious type could implement both the Car and Boat traits. It would be a kind of Car and a kind of Boat. In Rust, some traits implement more ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access