Which of the following best explains why enums are used in Rust?
Think about how enums help organize different but related data options.
Enums let you define a type that can be one of several variants. This helps write safer code by handling all possible cases explicitly.
What is the output of this Rust code?
enum Direction { North, South, East, West, } fn main() { let dir = Direction::East; match dir { Direction::North => println!("Going North"), Direction::South => println!("Going South"), Direction::East => println!("Going East"), Direction::West => println!("Going West"), } }
Look at the value assigned to dir and which match arm it triggers.
The variable dir is set to Direction::East, so the match prints "Going East".
What error will this Rust code produce?
enum Status { Ok(u32), Err(String), } fn main() { let s = Status::Ok(200); match s { Status::Ok(code) => println!("Code: {}", code), Status::Err(msg) => println!("Error occurred"), } }
Check how the Status::Err variant is matched compared to its definition.
The Status::Err variant carries a String value, so the match arm must include a variable to capture it, e.g., Status::Err(msg).
Consider this Rust enum. How many distinct variants does it have?
enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32), }
Count each variant name listed inside the enum.
The enum has four variants: Quit, Move, Write, and ChangeColor.
Why might a Rust programmer prefer using an enum instead of multiple separate structs for related data?
Think about how enums help the compiler check all possible cases.
Enums group related variants into one type, so the compiler can ensure all cases are handled, making code safer and easier to maintain.
