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, ...

Get Rust Essentials - 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.