Lesson 11 of 20

Enums

Enums

Enums let a type have one of several variants. Rust enums are much more powerful than in most languages — each variant can carry data.

Basic Enum

enum Direction {
    North,
    South,
    East,
    West,
}
let dir = Direction::North;

Enums with Data

Variants can hold different types and amounts of data:

enum Message {
    Quit,                      // unit variant
    Move { x: i32, y: i32 },  // struct variant
    Write(String),             // tuple variant
    Color(u8, u8, u8),        // tuple variant with multiple fields
}

impl for Enums

impl Direction {
    fn is_vertical(&self) -> bool {
        matches!(self, Direction::North | Direction::South)
    }
}

match on Enums

The compiler enforces that all variants are handled:

let msg = Message::Write(String::from("hello"));
match msg {
    Message::Quit => println!("quit"),
    Message::Move { x, y } => println!("move to {},{}", x, y),
    Message::Write(text) => println!("write: {}", text),
    Message::Color(r, g, b) => println!("color: {},{},{}", r, g, b),
}

Your Task

  1. Implement a Direction enum with North, South, East, West variants and methods:

    • opposite(&self) -> Direction
    • to_str(&self) -> &str
  2. Implement a Shape enum with Circle(f64), Rectangle(f64, f64), and Triangle(f64, f64, f64) variants and:

    • area(&self) -> f64 — use Heron's formula for triangles: s = (a+b+c)/2, area = sqrt(s*(s-a)*(s-b)*(s-c))
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.