Trait Bounds
Hard
+4 pts
🎯 In Python, function signatures don't constrain what types are allowed:
def largest(items):
return max(items) # works if items support comparison, crashes if not
largest([3, 1, 4]) # 4
largest(["a", "c", "b"]) # "c"
largest([{}, {}]) # TypeError at runtime
You find out about type mismatches when the code runs. Type hints help, but they're advisory:
from typing import TypeVar
T = TypeVar("T", bound=Comparable)
def largest(items: list[T]) -> T:
return max(items)
Rust's trait bounds serve the same purpose — but they're enforced by the compiler. If a type doesn't meet the bounds, the code won't compile.
Basic bounds
A trait bound constrains a type parameter to types that implement specific traits:
fn print_it<T: Display>(item: T) {
println!("{}", item);
}
T: Display means "T must implement Display." You …
Login to see the full exercise.
Topics