Logo

Developer learning path

Rust

Trait Bounds in Rust

Trait Bounds

21

#description

In Rust programming language, trait bounds are a way of specifying constraints on the types that can be used as parameters or return values in a function or struct. A trait is a set of methods that define a behavior or capability, and a “trait bound” specifies that a generic type parameter must implement one or more traits.

For example, if you define a generic function that operates on a particular type, you can use a trait bound to specify that the type must implement a particular trait. This improves code safety by preventing the rust compiler from allowing mismatches between types that can't be operated on using the method implementations of your functions.

Let's say, you have two structs Rectangle and Circle with an area method. You can define a trait Area that will have the area method signature. Then you can implement this trait for both Rectangle and Circle structs. Now you can define a generic function that takes any type that implements the Area trait. This means that any struct with an area method can be passed as an argument to this function.

                    
trait Area {
    fn area(&self) -> f64;
}

struct Rectangle {
    width: f64,
    height: f64,
}

struct Circle {
    radius: f64,
}

impl Area for Rectangle {
    fn area(&self) -> f64 {
        self.width * self.height
    }
}

impl Area for Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * (self.radius * self.radius)
    }
}

fn print_area<T: Area>(shape: &T) {
    println!("The area of the shape is {}", shape.area());
}

fn main() {
    let rect = Rectangle { width: 4.0, height: 5.0 };
    let circle = Circle { radius: 3.0 };
    
    print_area(&rect); // prints "The area of the shape is 20"
    print_area(&circle); // prints "The area of the shape is 28.274333882308138"
}
                  

In the code above, print_area is a generic function that takes a reference to a type that implements the Area trait. The trait bound T: Area specifies that the type parameter T must implement the Area trait.

Using trait bounds improves code safety and makes it easier to write generic code that can work with a wider range of data types.

March 27, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.