Use traits and generics
Write reusable behavior with trait bounds.
- 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.
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}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 XPTrait bound decision flow
Follow how a generic helper picks the bound it needs to compile.
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.
Pick the larger integer
Implement max_i32(a, b) returning the larger of two i32 values and print it.
- Bigger second
- Bigger first
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…