O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Traits and implementations

Traits and implementations are similar to interfaces and classes that implement those interfaces in object-oriented languages. Even though object-oriented is a very liberal term, which might mean lots of different things, here are some key differences between typical OO languages and Rust:

  • Even though traits have a form of inheritance in Rust, implementations do not. Therefore, composition is used instead of inheritance.
  • You can write implementation blocks anywhere, without having access to the actual type.

The syntax for trait blocks defines a set of types and methods. A very simple trait declaration would look as follows:

trait TraitName {    fn method(&self); } 

An implementation for this trait would need to ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required