Rust Fundamentals · 10 XP Pro
if and else
if runs a block only when its condition is true. The condition must be a
bool: Rust never treats numbers or strings as truthy. Chain extra cases with
else if, and finish with else as the catch-all.
let temp = 18;
if temp < 10 {
println!("coat");
} else if temp < 20 {
println!("jumper");
} else {
println!("t-shirt");
}
In Rust, if is an expression: it produces a value. Every branch must give
the same type, and you leave off the semicolon on the value you want to hand back.
let label = if temp < 15 { "cool" } else { "warm" };
Because a function body is also an expression, an if chain can be the last thing
in a function with no return at all.
Your task
- Write
ticket_price(age: u32) -> u32. Under 5 years old is free (0), ages 5 to 12 pay8, ages 13 to 64 pay15, and 65 or older pay10. - Write
larger(a: i32, b: i32) -> i32that returns the bigger of the two using anifexpression (do not usemax).