O'Reilly logo

Rust Essentials - Second Edition by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required