Complete the code to match the enum variant and print a message.
enum Direction {
North,
South,
East,
West,
}
fn main() {
let dir = Direction::North;
match dir {
Direction::North => println!("You are heading [1]."),
_ => println!("Other direction."),
}
}The match arm for Direction::North prints "You are heading north." so the blank should be filled with "north".
Complete the match expression to handle the Color enum and print the color name.
enum Color {
Red,
Green,
Blue,
}
fn main() {
let c = Color::Green;
match c {
Color::Red => println!("Color is Red"),
Color::Green => println!("Color is [1]"),
Color::Blue => println!("Color is Blue"),
}
}The message prints a string, so the color name must be a string literal with quotes. "green" is correct.
Fix the error in the match expression by completing the blank.
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"),
Message::Move {{ x, y }} => println!("Move to x: [1], y: {}", y),
Message::Write(text) => println!("Write message: {}", text),
}
}The placeholder in the format string expects a variable for x coordinate. The variable is x extracted from the Move variant.
Fill both blanks to complete the match arms for the enum Result with Ok and Err variants.
enum Result<T, E> {
Ok(T),
Err(E),
}
fn main() {
let res: Result<i32, &str> = Result::Ok(42);
match res {
Result::Ok(value) => println!("Success with value: [1]"),
Result::Err(error) => println!("Error: [2]"),
}
}The placeholders should be replaced with the variable names value and error extracted from the enum variants.
Fill all three blanks to complete the match expression for the enum Shape with different variants.
enum Shape {
Circle(f64),
Rectangle { width: f64, height: f64 },
Square(f64),
}
fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14 * [1] * [2],
Shape::Rectangle { width, height } => [3] * height,
Shape::Square(size) => size * size,
}
}For Circle, area is π * radius * radius, so both blanks are radius. For Rectangle, area is width * height, so the blank is width.
