January 2019
Beginner to intermediate
554 pages
13h 31m
English
We can also specify multiple trait bounds to a generic type using the + symbol. Let's take a look at the impl block for the HashMap type from the standard library:
impl<K: Hash + Eq, V> HashMap<K, V, RandomState>
Here, we can see that K, denoting the type of the HashMap key, has to implement the Eq trait, as well as the Hash trait.
We can also combine traits to create a new trait, that represents all of them:
// traits_composition.rstrait Eat { fn eat(&self) { println!("eat"); }}trait Code { fn code(&self) { println!("code"); }}trait Sleep { fn sleep(&self) { println!("sleep"); }}trait Programmer : Eat + Code + Sleep { fn animate(&self) { self.eat(); self.code(); self.sleep(); println!("repeat!"); }}struct ...Read now
Unlock full access