Loading
0x80Lesson 9 of 17

Use traits and generics

Write reusable behavior with trait bounds.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Define generic functions constrained by traits.

Generics let one function work for many types. Traits define required behavior. Together, trait bounds like T: PartialOrd express what operations generic code may use.

main.rs
1fn max_value<T: PartialOrd + Copy>(a: T, b: T) -> T {
2    if a > b { a } else { b }
3}
4
5fn main() {
6    println!("{}", max_value(3, 9));
7}
Output
9

Trait bounds are contracts: they make reusable code explicit and type-safe. Start with standard traits like PartialOrd, Display, and Clone.

Try it

Up to 15 XP

Trait bound decision flow

Follow how a generic helper picks the bound it needs to compile.

Message 1 of 3Predicted 0/0
Generic function
Compiler
Trait system

Key takeaways

  • Define generic functions constrained by traits.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Pick the larger integer

+25 XP

Implement max_i32(a, b) returning the larger of two i32 values and print it.

  • Bigger second
  • Bigger first
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…