What if you could write one function that safely works with many types without guessing or repeating code?
Why Trait bounds in Rust? - Purpose & Use Cases
Imagine you want to write a function that works with different types, but only if those types can do certain things, like being printed or compared. Without a clear way to say what types are allowed, you might try to write separate functions for each type or guess what will work.
Writing many versions of the same function for each type is slow and confusing. You might forget to handle a type or get errors only when running the program. It's like trying to fit square pegs in round holes without knowing which pegs fit.
Trait bounds let you say exactly what abilities a type must have to be used in your function. This way, the compiler checks for you, and you write one clear function that works safely with many types.
fn print_value(value: i32) { println!("{}", value); }
fn print_value_str(value: &str) { println!("{}", value); }fn print_value<T: std::fmt::Display>(value: T) { println!("{}", value); }You can write flexible, reusable code that works with many types while keeping safety and clarity.
Imagine a function that sorts a list of items. Using trait bounds, you ensure the items can be compared, so the function works for numbers, strings, or any custom type that knows how to compare itself.
Trait bounds specify what a type must be able to do.
They let you write one function for many types safely.
The compiler checks your rules, preventing errors early.