Rust - Traits
Questions
Are traits analogous to Abstract classes (or interfaces with implementations) in Java?
Reading material
Examples of Traits from Standard Library
- https://doc.rust-lang.org/std/marker/index.html#traits
- https://doc.rust-lang.org/std/marker/trait.Copy.html
Why do we need Traits in the first place?
Because, in Rust, we don’t have Object inheritance - or Struct inheritance.
- Traits are similar to
interfaces
in other languages. - Traits are similar to
interfaces
andAbstract Classes
in Java. - Traits define required behavior - functions and methods that a Struct must implement, if it wants to have that Trait.
Rust takes Composition over Inheritance
approach.
Another interesting thing about Rust traits: Traits implement inheritance.
Why bother with Traits? Why don’t we just write the impls in the Structs without using Traits?
With Traits, we can start writing generic functions that can be implemented by any Struct that wants to implement the Trait. As long as one of either the Trait or the Struct is defined in our project, we can implement any Trait for any Struct. That means, we can implement our Traits on any types from anywhere - including built-in types and types we import from some other package. And on the Structs, we can implement any Trait - whether built-in or from some other project.