Traits
What if our game is really diversely populated, and besides Aliens we have also Zombies and Predators, and, needless to say, they all want to attack. Can we abstract their common behavior into something they all share? Of course, in Rust we say that they have a trait in common, analogous to an interface or superclass in other languages. Let's call that trait Monster
, and because they all want to attack, a first version could be:
// see code in Chapter 6/code/traits.rs trait Monster { fn attack(&self); }
A trait mostly contains a description of methods, that is, their type declarations or signatures, but no real implementation (as we will see later in the example, a trait can contain a default implementation of a method). This is logical, because Zombies
, Predators
, and Aliens
could each have their own method of attack. So there is no code body between {}
after the function signature, but don't forget the ;
(semicolon) to close it off.
When we want to implement the Monster
...