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.rs struct 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 on T
. If it did, it wouldn't be generic at all, and would only be able to accept types that have the init()
method on them. So, there is a way that we can let the compiler know of this and constrain the set...