Bird
Raised Fist0
Rustprogramming~20 mins

Enums with data in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Enums Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust enum with data?
Consider the following Rust code using an enum with data. What will be printed when running this program?
Rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let msg = Message::Move { x: 10, y: 20 };
    match msg {
        Message::Quit => println!("Quit"),
        Message::Move { x, y } => println!("Move to ({}, {})", x, y),
        Message::Write(text) => println!("Write: {}", text),
        Message::ChangeColor(r, g, b) => println!("Change color to ({}, {}, {})", r, g, b),
    }
}
AMove to (10, 20)
BQuit
CWrite: Move
DChange color to (10, 20, 0)
Attempts:
2 left
💡 Hint
Look at the variant used and how the match arms print the values.
❓ Predict Output
intermediate
2:00remaining
What does this Rust enum with tuple data print?
Given this Rust code, what is the output when main runs?
Rust
enum Shape {
    Circle(f64),
    Rectangle(f64, f64),
}

fn main() {
    let shape = Shape::Rectangle(3.0, 4.0);
    match shape {
        Shape::Circle(radius) => println!("Circle with radius {}", radius),
        Shape::Rectangle(width, height) => println!("Rectangle {} x {}", width, height),
    }
}
ACircle with radius 3
BRectangle 4 x 3
CCircle with radius 4
DRectangle 3 x 4
Attempts:
2 left
💡 Hint
Check which variant is created and how the values are printed.
🔧 Debug
advanced
2:00remaining
Why does this Rust enum code fail to compile?
This Rust code tries to use an enum with data but does not compile. What is the cause of the error?
Rust
enum Command {
    Start(u32),
    Stop,
}

fn main() {
    let cmd = Command::Start;
    match cmd {
        Command::Start(time) => println!("Start at {}", time),
        Command::Stop => println!("Stop"),
    }
}
AEnum variants cannot have data
BMatch arms missing a wildcard pattern
CMissing value for Start variant when creating cmd
Dprintln! macro syntax error
Attempts:
2 left
💡 Hint
Look at how the Start variant is created and what data it expects.
📝 Syntax
advanced
2:00remaining
Which option correctly defines an enum with named fields in Rust?
Select the correct Rust enum definition that uses named fields for one variant.
Aenum Event { Click { x: i32, y: i32 }, KeyPress(char) }
Benum Event { Click(x: i32, y: i32), KeyPress(char) }
Cenum Event { Click(i32, i32), KeyPress { char } }
Denum Event { Click { x, y }, KeyPress(char) }
Attempts:
2 left
💡 Hint
Named fields require curly braces with field names and types.
🚀 Application
expert
2:30remaining
How many items are in the vector after filtering enum variants with data?
Given this Rust code, how many elements remain in the vector after filtering only the Message::Write variants?
Rust
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

fn main() {
    let messages = vec![
        Message::Quit,
        Message::Write(String::from("Hello")),
        Message::Move { x: 1, y: 2 },
        Message::Write(String::from("World")),
        Message::ChangeColor(255, 0, 0),
    ];

    let writes: Vec<&Message> = messages.iter().filter(|m| {
        match m {
            Message::Write(_) => true,
            _ => false,
        }
    }).collect();

    println!("Number of Write messages: {}", writes.len());
}
A0
B2
C1
D3
Attempts:
2 left
💡 Hint
Count how many Message::Write variants are in the vector.

Practice

(1/5)
1. What is the main purpose of enums with data in Rust?
easy
A. To group related values that can be different types under one name
B. To create multiple copies of the same data
C. To perform arithmetic operations on numbers
D. To store only strings in a list

Solution

  1. Step 1: Understand what enums with data do

    Enums with data allow each variant to hold different types or amounts of data, grouping related but different information.
  2. Step 2: Compare options with this understanding

    Only To group related values that can be different types under one name correctly describes grouping related values of different types under one name.
  3. Final Answer:

    To group related values that can be different types under one name -> Option A
  4. Quick Check:

    Enums with data = group different types [OK]
Hint: Enums group different data types under one name [OK]
Common Mistakes:
  • Thinking enums only store one data type
  • Confusing enums with arrays or vectors
  • Assuming enums perform calculations
2. Which of the following is the correct syntax to define an enum variant with data in Rust?
easy
A. enum Color { Red(u8, u8, u8), Blue }
B. enum Color { Red = (u8, u8, u8), Blue }
C. enum Color { Red: (u8, u8, u8), Blue }
D. enum Color { Red -> (u8, u8, u8), Blue }

Solution

  1. Step 1: Recall enum variant syntax with data

    In Rust, enum variants with data are defined by listing the variant name followed by parentheses containing the data types.
  2. Step 2: Check each option

    enum Color { Red(u8, u8, u8), Blue } uses correct syntax: Red(u8, u8, u8). Options A, B, and C use invalid syntax with ->, =, or : which are incorrect for enum variant data.
  3. Final Answer:

    enum Color { Red(u8, u8, u8), Blue } -> Option A
  4. Quick Check:

    Variant with data uses parentheses () [OK]
Hint: Use parentheses () after variant name for data [OK]
Common Mistakes:
  • Using = instead of () for variant data
  • Using : or -> which are invalid here
  • Forgetting parentheses for data
3. What will be the output of this Rust code?
enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
}

fn main() {
    let msg = Message::Move { x: 10, y: 20 };
    match msg {
        Message::Quit => println!("Quit"),
        Message::Move { x, y } => println!("Move to {}, {}", x, y),
        Message::Write(text) => println!("Write {}", text),
    }
}
medium
A. Compilation error
B. Quit
C. Write 10, 20
D. Move to 10, 20

Solution

  1. Step 1: Identify the enum variant used

    The variable msg is assigned Message::Move with x=10 and y=20.
  2. Step 2: Match arms and output

    The match statement checks msg. For Message::Move, it prints "Move to {}, {}" with x and y values, so output is "Move to 10, 20".
  3. Final Answer:

    Move to 10, 20 -> Option D
  4. Quick Check:

    Match Message::Move prints coordinates [OK]
Hint: Match variant and print its data fields [OK]
Common Mistakes:
  • Confusing variant names
  • Expecting Quit or Write output
  • Thinking code won't compile
4. The following Rust code has an error. What is the problem?
enum Shape {
    Circle(f64),
    Rectangle { width: f64, height: f64 },
}

fn area(shape: Shape) -> f64 {
    match shape {
        Shape::Circle(radius) => 3.14 * radius * radius,
        Shape::Rectangle(width, height) => width * height,
    }
}
medium
A. Missing semicolon after match arms
B. Circle variant should have named fields
C. Incorrect pattern for Rectangle variant in match
D. Function return type should be i32

Solution

  1. Step 1: Check enum variant definitions

    Circle has tuple data (f64), Rectangle has named fields { width, height }.
  2. Step 2: Check match patterns

    Circle pattern is correct. Rectangle pattern uses (width, height) which is wrong; it should use { width, height } to match named fields.
  3. Final Answer:

    Incorrect pattern for Rectangle variant in match -> Option C
  4. Quick Check:

    Match named fields with braces {} [OK]
Hint: Match named fields with braces {}, tuple fields with () [OK]
Common Mistakes:
  • Using parentheses for named fields
  • Ignoring pattern mismatch errors
  • Changing return type unnecessarily
5. Given this enum and function, what is the output?
enum Event {
    Click { x: i32, y: i32 },
    KeyPress(char),
    Resize(u32, u32),
}

fn describe(event: Event) -> String {
    match event {
        Event::Click { x, y } if x > 0 && y > 0 => format!("Clicked at positive coords: {}, {}", x, y),
        Event::Click { .. } => "Clicked at non-positive coords".to_string(),
        Event::KeyPress(c) if c.is_alphabetic() => format!("Key pressed: {}", c),
        Event::KeyPress(_) => "Non-alphabetic key pressed".to_string(),
        Event::Resize(w, h) if w == h => "Resized to square".to_string(),
        Event::Resize(_, _) => "Resized to rectangle".to_string(),
    }
}

fn main() {
    let e = Event::Resize(100, 100);
    println!("{}", describe(e));
}
hard
A. Clicked at positive coords: 100, 100
B. Resized to square
C. Resized to rectangle
D. Non-alphabetic key pressed

Solution

  1. Step 1: Identify the enum variant and values

    The event is Event::Resize with width=100 and height=100.
  2. Step 2: Match arms with conditions

    The Resize arm with condition w == h matches because 100 == 100, so it returns "Resized to square".
  3. Final Answer:

    Resized to square -> Option B
  4. Quick Check:

    Resize with equal sides = square [OK]
Hint: Check match guards (if conditions) carefully [OK]
Common Mistakes:
  • Ignoring if conditions in match arms
  • Confusing Resize with Click variant
  • Assuming default arm without conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard