Enums in Rust

Enums in Rust

Introduction

Enums in Rust, similar to other Programming languages, allow values to be grouped together.

Examples

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

fn main() {
    let light = TrafficLight::Red;

    match light {
        TrafficLight::Red => println!("Stop!"),
        TrafficLight::Yellow => println!("Prepare to stop or go with caution."),
        TrafficLight::Green => println!("Go!"),
    }
}

match in this case works similar to switch in many other Programming languages. Hence output will be Stop!

Now enums can also be typed, like below.

struct Sprite {
    name: String,
    health: u64
}

enum Characters {
    Hero(Sprite),
    Enemy(Sprite),
    Boss(Sprite)
}

fn main() {
    let hero_sprite = Sprite {
        name: String::from("Jason"),
        health: 100
    };

    let boss_sprite = Sprite {
        name: String::from("Hydra"),
        health: 500
    };

    let hero_character = Characters::Hero(hero_sprite);
    let boss_character = Characters::Boss(boss_sprite);

    gameplay_description(hero_character);
    gameplay_description(boss_character);
}

fn gameplay_description (character: Characters) {
    match character {
        Characters::Hero(sprite) => println!("{} has arrived.", sprite.name),
        Characters::Enemy(sprite) => println!("It's a no name Enemy."),
        Characters::Boss(sprite) => println!("Beware of {}!", sprite.name),
    }
}

So we have enum Characters and each value is of the struct Sprite type

Now you can add more fields and values depending on the need of your game.

In the struct Sprite type you can add special moves, abilities, etc. In the enum Characters you can add more values like Professor, MysteryMan, etc. to make your game a lil bit better than what we have here.

Now here all values in enum Characters are of the same type, but they can have different types also. This is an example from the Rust Book.

enum IpAddr {
    V4(u8, u8, u8, u8),
    V6(String),
}

let home = IpAddr::V4(127, 0, 0, 1);

let loopback = IpAddr::V6(String::from("::1"));

Conclusion

That's the basic idea of enums for now. We'll be using enums a lot more in the coming articles. Cheers!