Ad space (banner)
Lesson 16 / 20

Traits

This lesson covers the trait, which gives several types a shared behaviour.

A trait is close to an interface in other languages: it defines the promise that "this type has these methods". You supply the implementation for a concrete type by writing impl TraitName for TypeName.

The sample code defines trait Speak { fn speak(&self) -> String; } and implements it for a Dog struct with impl Speak for Dog.

A common early stumble is that the trait's declaration (what a type should be able to do) is separate from its implementation (how it actually works). That separation is also what lets you add new behaviour to an existing type after the fact.

In professional work, traits are used widely wherever several types need a shared interface — "can be displayed", "can be compared", and so on.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Rust directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)