Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 132 ยท Structs, Enums and Traits Basics

Traits

Learn Rust traits - define and implement them, default methods, trait bounds, the orphan rule, derive macros (Debug, Clone, PartialEq, Hash, Ord, Default) and a tour of standard traits.

A dog, a robot and a radio can all "make a sound", but they have nothing else in common. In many languages you would force them under a shared parent class. Rust takes a different route: a trait describes a capability, a set of methods that a type promises to provide, and any type can implement any number of traits, independently of how it was defined. Traits are Rust's tool for shared behavior, they power generics and operator overloading, and the standard library is built from them (Display, Clone, Iterator, Add, ...).

This lesson covers defining and implementing traits, default methods, using traits as bounds, the orphan rule that limits who may implement what, #[derive] for the common standard traits, and a tour of the traits you will meet daily. Later lessons go deeper: Trait Objects, Generics and Trait Bounds and where Clauses.

Defining and implementing a trait

A trait lists method signatures. A type provides the bodies in an impl Trait for Type block:

Rust A first trait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Dog and Robot are unrelated types, yet both can speak(). The trait is like a contract: the compiler refuses an impl that misses a method or has a different signature.

Rust Incomplete trait implementation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0046]: not all trait items implemented, missing: `name`
 --> main.rs:8:1
  |
3 |     fn name(&self) -> String;
  |     ------------------------- `name` from trait
...
8 | impl Shape for Square {
  | ^^^^^^^^^^^^^^^^^^^^^ missing `name` in implementation

Default methods

A trait can provide a body for a method. Implementors get it for free and may override it. Default methods can call the trait's other methods, which lets you require a minimal set of methods and build a rich API on top:

Rust Default methods build on required ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard Iterator trait works exactly this way: you write next() and receive dozens of methods like map, filter and sum (Iterators).

Traits in scope

To call a trait's method you must have the trait in scope. Your own trait in the same file is already visible. For traits from other modules you need use. Many common ones (Clone, Iterator, Default, ...) are in the prelude, which Rust imports automatically. If you see no method named ... found and the method exists on a trait, a missing use is the usual cause; the compiler even suggests the import.

Traits as parameters

A function can say "give me anything that implements this trait". This is a trait bound. You will study bounds in detail later; here are the two spellings:

Rust Accepting any type with a trait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For each concrete type you use, the compiler generates a specialized copy of the function (monomorphization), so a call through a bound is as fast as a hand-written one. If you need a list holding different types, see Trait Objects and Dynamic Dispatch.

The orphan rule

You may implement a trait for a type only if your crate defines the trait or the type (or both). You cannot implement a foreign trait for a foreign type:

Rust Foreign trait for a foreign type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> main.rs:3:1
  |
3 | impl fmt::Display for Vec<i32> {
  | ^^^^^^^^^^^^^^^^^^^^^^--------
  |                       |
  |                       `Vec` is not defined in the current crate
  |
  = note: define and implement a trait or new type instead

Why? If two libraries could both implement Display for Vec<i32>, which one wins when you use both? The rule keeps implementations coherent. The workaround is a newtype, a tuple struct wrapping the foreign type, which is your own type:

Rust The newtype workaround

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

(impl Display for Numbers is fine: the type is ours. And your own trait for Vec<i32> is fine too, because the trait is ours.) See Advanced Traits for more on newtypes.

Derivable traits

Many standard traits have a mechanical implementation, so the compiler writes it for you when you add #[derive(...)]. A struct or enum can derive a trait only if all its fields implement it:

Trait What it gives you Typical use
Debug {:?} and {:#?} output every type
Clone .clone(), explicit deep copy duplicating values
Copy implicit bitwise copy instead of move (needs Clone) small plain-data types
PartialEq / Eq == and != comparing values; Eq promises full equality (no NaN-like values)
PartialOrd / Ord <, >, sort(), max() ordering
Hash usable as a HashMap key or in a HashSet keys
Default Type::default() zero or empty values
Rust Deriving common traits

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For structs the derived PartialOrd/Ord compare field by field in declaration order. That is why 1.10.2 > 1.4.0 here: major ties, then minor 10 beats 4. If you reorder the fields, you change the ordering. For enums the order is the order of the variants.

What derive does not do

Derive requires every field to support the trait. A struct with an f64 field cannot derive Eq, Ord or Hash, because floats have NaN:

Rust Deriving Eq with a float field (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0277]: the trait bound `f64: Eq` is not satisfied
 --> main.rs:3:5
  |
1 | #[derive(PartialEq, Eq)]
  |                     -- in this derive macro expansion
2 | struct Reading {
3 |     celsius: f64,
  |     ^^^^^^^^^^^^ the trait `Eq` is not implemented for `f64`

You can still derive PartialEq and PartialOrd, which allow == and < without promising the stronger guarantees. And #[derive(Default)] on an enum needs one variant marked #[default]:

Rust Default on an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

A tour of standard traits

You will implement or use these constantly; most get their own lessons.

Implementing your trait for built-in types

Rust Implementing traits for built-in types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Adding methods to existing types through your own trait is called an extension trait; it is common and explained in Advanced Trait Techniques.

Design notes

  • Keep traits small. One capability per trait (Read, Write) composes better than one giant interface.
  • Prefer default methods to give implementors a minimal required surface.
  • Name by capability: a method name that reads well (speak, area), and trait names as nouns or adjectives (Iterator, Clone, Display).
  • Static dispatch by default. Generic bounds are zero-cost; use dyn Trait only when you need a heterogeneous collection or want to reduce code size.
  • Derive early. Add Debug immediately; add Clone, PartialEq and friends when needed, since removing a derive later can break users of a public type.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the compiler require when you write impl Shape for Square?

    An impl must provide all required methods (E0046 otherwise). Methods with default bodies may be omitted or overridden.
  2. 2. What is the orphan rule?

    The rule prevents two crates from providing conflicting implementations. Wrap a foreign type in your own newtype to implement a foreign trait for it.
  3. 3. In which order does a derived PartialOrd compare the fields of a struct?

    Derived ordering is lexicographic in declaration order: the first field decides, ties go to the second, and so on.
  4. 4. Why can a struct with an f64 field not derive Eq?

    Eq promises that x == x is always true. NaN breaks that, so floats implement PartialEq and PartialOrd but not Eq or Ord.
  5. 5. Which spelling accepts any type that implements the Area trait?

    impl Trait in argument position is shorthand for a generic parameter with a trait bound: fn show<T: Area>(s: &T).

Summary

  • A trait declares methods a type promises to provide; impl Trait for Type supplies them.
  • Default methods let implementors write a small core and receive a rich API.
  • Bound a parameter with impl Trait or T: Trait; the compiler monomorphizes, so it is zero-cost.
  • The orphan rule requires your crate to own the trait or the type; use a newtype to get around it.
  • #[derive] generates Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash and Default; derived ordering follows field declaration order.
  • Floats cannot be Eq, Ord or Hash; enums deriving Default need #[default].
  • Keep traits small and prefer static dispatch unless you need dyn.

Next: Trait Objects and Dynamic Dispatch