rustlings icon indicating copy to clipboard operation
rustlings copied to clipboard

Teach nested pattern matching in a new exercise

Open rishitc opened this issue 1 year ago • 1 comments

From the discussion in #2127, @mo8it suggested to open a issue for tracking the inclusion of an exercise for teaching nested pattern matching.

It's been a while since that discussion, but no issue was opened to track this; hence, I opened an issue to track it.

I myself recently finished the Rustlings exercises and I came up with the below execrise which I think will help teach the concept of nested pattern matching to newcomers.

I'm sharing the source code, below:

// Author: Rishit Chaudhary
// Date: 9th November 2024

enum Color {
    Rgb(u8, u8, u8),
    Hsl(u8, u8, u8),
}

struct Position {
    x: i32,
    y: i32,
}

enum Command {
    Quit,
    Move(Position),
    Write(String, Position),
    ChangeColor(Color, Position),
}

fn main() {
    let cmds = &[
        Command::ChangeColor(Color::Hsl(0, 160, 255), Position { x: 1, y: 10 }),
        Command::ChangeColor(Color::Rgb(0, 160, 255), Position { x: 1, y: 10 }),
        Command::Move(Position { x: 1, y: 10 }),
        Command::Write("Hello".into(), Position { x: 1, y: 10 }),
        Command::Quit,
    ];

    for cmd in cmds {
        match cmd {
            Command::ChangeColor(Color::Rgb(r, g, b), Position { x, y }) => {
                println!("Change color of position ({x}, {y}) to red {r}, green {g}, and blue {b}");
            }
            Command::ChangeColor(Color::Hsl(h, s, l), Position { x, y }) => {
                println!(
                    "Change color of position ({x}, {y}) to hue {h}, saturation {s}, lightness {l}"
                )
            }
            Command::Write(text, Position { x, y }) => {
                println!("Write text \"{text}\" to position ({x}, {y}).")
            }
            Command::Move(Position { x, y }) => {
                println!("Move to position ({x}, {y}).")
            }
            Command::Quit => {
                println!("Goodbye!")
            }
        }
    }
}

Here's the Rust Playground link to the above code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=651e559640d308b05967d2aef512bbbe

If you think this code can be added as a new exercise; I'd be happy to add the required comments explaining the exercise, and create a PR to contribute it as per the guidelines mentioned in Contributing to Rustlings.

Let me know if you have any questions or suggestions, I'd be happy to help

Thanks

rishitc avatar Nov 09 '24 09:11 rishitc

I will take a look at new exercises in December ;)

mo8it avatar Nov 11 '24 12:11 mo8it