Traits

Get introduced to traits, an exciting feature enabling code reusability and polymorphism.

Traits are extremely useful in Rust as they allow us to do different things. One of the things, for example, is an interface definition. They allow us to define a shared interface for methods that different types need to implement. Those types could be a structure or an enum, for example. In this lesson, we will build a trait for an enum and see how it works.

Note: In Rust, there's no direct equivalent for interfaces as there is in other languages, like C#, however, by making use of traits, we can achieve similar functionality. By building a trait for a type, we specify the functionality that the type is supposed to provide.

Code implementation

In Rust, we can use traits to define a specific behavior for different types. They allow us to declare methods that types can implement, providing a form of code reuse. Traits are similar to interfaces in other programming languages. Let’s create a Character enum with different variants and learn how we can use a trait with it.

Get hands-on with 1400+ tech skills courses.