Trait bounds help us tell Rust what abilities a type must have to be used in a function or struct. This keeps code safe and clear.
0
0
Trait bounds in Rust
Introduction
When writing a function that works with different types but needs certain features, like printing or comparing.
When creating a struct that holds generic types but requires those types to have specific methods.
When you want to make sure a type can be cloned or copied before using it in your code.
When you want to restrict a generic type to only those that implement a certain trait, like Iterator.
When you want to use methods from a trait on a generic type inside a function.
Syntax
Rust
fn function_name<T: TraitName>(param: T) {
// function body
}
// Or multiple traits:
fn function_name<T: Trait1 + Trait2>(param: T) {
// function body
}The T: TraitName means type T must implement TraitName.
You can require multiple traits by using + between them.
Examples
This function prints any value that can be displayed as text.
Rust
fn print_value<T: std::fmt::Display>(value: T) {
println!("Value: {}", value);
}This function compares two values and prints the result. The values must be displayable and comparable.
Rust
fn compare_and_print<T: std::fmt::Display + PartialOrd>(a: T, b: T) {
if a > b {
println!("{} is greater than {}", a, b);
} else {
println!("{} is not greater than {}", a, b);
}
}This struct holds a generic item that can be cloned. The method duplicates the item.
Rust
struct Container<T: Clone> {
item: T,
}
impl<T: Clone> Container<T> {
fn duplicate(&self) -> (T, T) {
(self.item.clone(), self.item.clone())
}
}Sample Program
This program defines a function that prints any displayable item twice. It shows how trait bounds let us use different types safely.
Rust
fn print_twice<T: std::fmt::Display + Copy>(item: T) {
println!("First: {}", item);
println!("Second: {}", item);
}
fn main() {
print_twice(10);
print_twice("hello");
}OutputSuccess
Important Notes
Trait bounds ensure your code only uses types with the needed abilities, preventing errors.
You can also write trait bounds on structs and impl blocks, not just functions.
Using trait bounds helps Rust check your code at compile time, making it safer.
Summary
Trait bounds tell Rust what traits a generic type must have.
They let you write flexible but safe code that works with many types.
You use T: TraitName syntax to add trait bounds.