Skip to content
Guest
Rust · Course Syllabus Show lessons
Abstractions · 10 min read · Intermediate

Traits, Generics & Trait Bounds

Write reusable zero-cost generic functions constrained by traits (Rust's equivalent of interfaces).

What you'll learn

  • Define shared behavior with trait declarations and impl Trait for Type
  • Constrain generic type parameters with where clauses
  • Understand static dispatch (monomorphization) vs dynamic dispatch (dyn Trait)

Overview

Write reusable zero-cost generic functions constrained by traits (Rust’s equivalent of interfaces).

Code Example

trait Summarize {
    fn summary(&self) -> String;
}

fn print_card<T: Summarize>(item: &T) {
    println!("{}", item.summary());
}

Key Takeaways

  • Define shared behavior with trait declarations and impl Trait for Type
  • Constrain generic type parameters with where clauses
  • Understand static dispatch (monomorphization) vs dynamic dispatch (dyn Trait)

Quick Check

Check Your Understanding

Score: 0 / 1

1. Why are Rust generics with trait bounds (`fn f<T: Trait>(x: &T)`) called 'zero-cost abstractions'?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind