Trait bounds on generic functions and impl blocks

This is the most common place where trait bounds are used. We can specify trait bounds on functions and also on generic implementations, as shown in the following example:

// trait_bounds_functions.rs

use std::fmt::Debug;

trait Eatable {
fn eat(&self);
}

#[derive(Debug)]
struct Food<T>(T);

#[derive(Debug)]
struct Apple;

impl<T> Eatable for Food<T> where T: Debug {
fn eat(&self) {
println!("Eating {:?}", self);
}
}

fn eat<T>(val: T) where T: Eatable {
val.eat();
}

fn main() {
let apple = Food(Apple);
eat(apple);
}

We have a generic type Food and a specific food type Apple that we put into a Food instance and bind to variable apple. Next, we call the generic method eat, passing apple. Looking at the signature of eat, the type T has to be Eatable. To make apple eatable, we implement the Eatable trait for Food, also specifying that our type has to be Debug to make it printable to the console inside our method. This is a dumb example but demonstrates the idea.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset