Using traits with generics – trait bounds

Now that we have a decent idea about generics and traits, we can explore ways in which we can combine them to express more about our interfaces at compile time. Consider the following code:

// trait_bound_intro.rsstruct Game;struct Enemy;struct Hero;impl Game {    fn load<T>(&self, entity: T) {        entity.init();    }}fn main() {    let game = Game;    game.load(Enemy);    game.load(Hero);}

In the preceding code, we have a generic function, load, on our Game type that can take any game entity and load it in our game world by calling init() on all kinds of T. However, this example fails to compile with the following error:

So, a generic function taking any type T cannot know or assume by default the init method exists ...

Get Mastering Rust - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.