Rust - Traits

Questions

Are traits analogous to Abstract classes (or interfaces with implementations) in Java?

Reading material

  1. https://doc.rust-lang.org/book/ch10-02-traits.html

Examples of Traits from Standard Library

  1. https://doc.rust-lang.org/std/marker/index.html#traits
  2. 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.

  1. Traits are similar to interfaces in other languages.
  2. Traits are similar to interfaces and Abstract Classes in Java.
  3. 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.

TODO

  1. https://blog.rust-lang.org/2015/05/11/traits.html