January 2019
Beginner to intermediate
554 pages
13h 31m
English
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.rsuse 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 ...
Read now
Unlock full access