Creating tetriminos

We wrote the type that will be used in our game, but we didn't write its initialization/creation yet. This is where Rust traits will be useful.

Let's start by writing a generator trait that will be implemented on all tetriminos:

trait TetriminoGenerator {
    fn new() -> Tetrimino;
}

And that's it. This trait just provides a function that creates a new Tetrimino instance. It maybe doesn't like this very much, but thanks to this trait, we'll be able to easily create all our tetriminos.

Time to write our first tetrimino:

struct TetriminoI;

No need to look for more code, this is what a tetrimino really looks like. It's an empty structure. The interesting part comes just after:

impl TetriminoGenerator for TetriminoI {
    fn new() ...

Get Rust Programming By Example 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.