Lesson 16 of 20
Generics
Generics
Generics let you write code that works for many types without duplication.
Generic Functions
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
The <T: PartialOrd> syntax means "T must implement PartialOrd" — required for the > comparison.
Generic Structs
struct Pair<T> {
first: T,
second: T,
}
impl<T: std::fmt::Display + PartialOrd> Pair<T> {
fn cmp_display(&self) {
if self.first >= self.second {
println!("Largest: {}", self.first);
} else {
println!("Largest: {}", self.second);
}
}
}
Monomorphization
Rust monomorphizes generic code at compile time — it creates a specialized version for each concrete type used. This means generics have zero runtime cost compared to writing type-specific code.
Multiple Type Parameters
struct Pair<T, U> {
first: T,
second: U,
}
Your Task
largest<T: PartialOrd>(list: &[T]) -> &T— returns a reference to the largest element.- Implement a generic
Stack<T>with:new() -> Selfpush(&mut self, item: T)pop(&mut self) -> Option<T>peek(&self) -> Option<&T>is_empty(&self) -> boolsize(&self) -> usize
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.