OpenViSTAI · Agents · Blockchain · Crypto
Menu

OPENVIST LEARN · FREE LESSONS

Traits and behaviour contracts

Use a trait bound to require a behaviour.

Lesson 22 of 30 · About 20 minutes · Beginner · English

By the end of this lesson

Use a trait bound to require a behaviour.

Before you start

  • Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
  • Complete lesson 21, or be comfortable explaining and running its examples.

Three words to know

Trait
A named set of behaviours implemented by types.
Implementation
Code supplying those behaviours for a type.
Trait bound
A requirement placed on a generic type.

1. Understand the idea

A trait describes what a type can do. Generic code may rely on a trait only when its bound says so. This gives the compiler a checkable contract. Traits do not require inheritance trees: a type can implement several independent behaviours. Avoid designing a large abstraction before you have a concrete repeated need.

2. Save, run and observe

Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.

Require a labelRUST · save as lesson.rs
trait Label { fn label(&self) -> &str; }
struct Queue;
impl Label for Queue { fn label(&self) -> &str { "ready" } }
fn show<T: Label>(value: &T) { println!("{}", value.label()); }
fn main() { show(&Queue); }
What you should see · example output
ready
Compile and run on macOS/LinuxTERMINAL · Bash or Windows PowerShell
rustc --edition=2024 lesson.rs -o lesson
./lesson

3. Explain the result

show can call label because T: Label requires it. Queue supplies the behaviour in its impl block. &self means the operation borrows its receiver. Another type can implement Label differently without changing show.

YOUR TURN

A small check before you continue

Can show accept an arbitrary integer in this program?

Show a suggested answer

No. No Label implementation exists for that integer type here. The bound is a compile-time requirement.

Sources and scope

Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.