Rust Fundamentals · 15 XP Pro

Enums

A struct groups values that exist together. An enum describes a value that is exactly one of a fixed set of possibilities, called variants. Variants are reached through the enum's name:

enum Light {
    Red,
    Green,
}

let now = Light::Green;

Enums are ordinary types, so they can be function parameters, return values and struct fields. The #[derive(Debug, PartialEq, Clone, Copy)] line you will see above an enum lets tests print it, compare it with ==, and copy it freely. Traits are explained later; for now just keep that line in place.

To look at which variant you have, use match (covered in depth soon):

fn next(l: Light) -> Light {
    match l {
        Light::Red => Light::Green,
        Light::Green => Light::Red,
    }
}

Your task

The starter already declares Direction and a Robot struct. Everything the tests use must be pub, so keep the pub keywords. Implement:

  1. pub fn turn_right(d: Direction) -> Direction: North becomes East, East becomes South, South becomes West, West becomes North.
  2. pub fn advance(robot: &mut Robot): move the robot one unit in the direction it faces. North is y + 1, East is x + 1, South is y - 1, West is x - 1. The robot keeps facing the same way.

Next lesson →

Sign in to run your code. It's free.