Search⌘ K
AI Features

Trait Bounds

Explore how to apply trait bounds in Rust to restrict generic type parameters. Understand how to ensure functions only accept types implementing required traits, enhancing type safety and code flexibility.

We'll cover the following...

I want to quadruple my numbers. I could do * 4, but that’s so pedestrian. I’ve already got a double method. So why not simply call it twice?

Rust 1.40.0
fn quadruple(x: i32) -> i32 {
x.double().double()
}
fn main() {
println!("quadruple 5_i32 == {}", quadruple(5_i32));
}
trait Double {
fn double(&self) -> Self;
}
impl Double for i32 {
fn double(&self) -> Self {
self * 2
}
}
impl Double for i64 {
fn double(&self) -> Self {
self * 2
}
}

That’s great, but ...