Complete these tasks to reinforce what you learned in this module.
Write a function double_if_some(opt: Option<i32>) -> Option<i32> that returns Some(2 * n) when opt is Some(n), and None when opt is None. In main, call it with Some(21) and print the result using match.
match on the Option; in the Some arm you can bind the inner value and return a new Some. For None, return None.// Task 1: Option and match. See tasks/TASKS.md.
fn main() {
todo!("Implement double_if_some and call with Some(21)");
}
Define an enum Direction { Up, Down, Left, Right }. Write a function delta(d: Direction) -> (i32, i32) that returns (dx, dy): Up = (0, -1), Down = (0, 1), Left = (-1, 0), Right = (1, 0). Call with Direction::Right and print the tuple.
(dx, dy) for each variant. The expected output tells you the mapping for Right.// Task 2: match on Direction. See tasks/TASKS.md.
fn main() {
todo!("Define Direction, delta(), call and print");
}
An enum Coin { Penny, Nickel, Dime, Quarter } is provided in the editor. Implement fn value_cents(c: Coin) -> u32 that returns each coin's value: Penny = 1, Nickel = 5, Dime = 10, Quarter = 25. This task is graded by hidden tests that check every variant.
match c { Coin::Penny => 1, ... }. A match must cover every variant, so the compiler stops you from forgetting one (exhaustiveness).// Task 3: implement value_cents, graded by HIDDEN tests. See tasks/TASKS.md.
#[derive(Clone, Copy)]
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_cents(c: Coin) -> u32 {
todo!("match on the coin and return its value in cents");
}
fn main() {
// `cargo test` ignores main; it's here so this file also builds as a binary.
println!("dime = {}", value_cents(Coin::Dime));
}