Rust, lesson 4
Programs constantly choose between paths. Rust gives you if for yes/no questions and
match for picking one of many cases.
No parentheses are needed around the condition, but braces are always required. Rust checks the conditions in order and runs the first block that matches.
The condition must be a bool. Rust will not treat 0 or an empty string as false;
if count { ... } is a compile error. Write if count != 0.
==, !=, <, <=, , compare values of the . Strings compare too, in
dictionary order: .
2 exercises to try what you just read.
>>="apple" < "banana"Combine conditions with && (and), || (or) and ! (not). && and || short-circuit:
the right side is skipped when the left side already decides the answer.
In Rust, if produces a value, so you can use it on the right side of let. Both branches
must give the same type, and the last expression in each block (with no semicolon) is the
value:
This replaces the "ternary operator" found in other languages. The semicolon rule matters:
a line ending in ; is a statement that produces nothing, while a line without one is the
block's value.
match compares a value against a list of patterns and runs the first arm that fits.
Each arm is pattern => expression. A pattern can be a single value, several values joined
with |, or a range:
1..=5 is an inclusive range (1 through 5). The _ pattern matches anything; it is the
catch-all.
match must be exhaustive: every possible value has to be covered by some arm. For an
i32, that means you almost always need a _ arm. The compiler refuses to build a match
that misses a case, which turns a whole category of bugs into compile errors.
A match guard adds an extra condition with if:
Matching on strings works with string literals: match command { "start" => ..., _ => ... }.
When your value is a String, match on command.as_str().
Read a temperature in degrees Celsius (a whole number, possibly negative) and print one word:
coat if it is below 5jacket if it is from 5 up to 17 (inclusive)t-shirt if it is from 18 up to 29 (inclusive)shade if it is 30 or moreSample input:
Sample output:
Read a year and print leap or common. A year is a leap year if it is divisible by 4,
except years divisible by 100, which are leap years only if also divisible by 400. Use if
as an expression to choose the word.
Sample input:
Sample output:
if temp > 30 {
println!("Hot!");
} else if temp > 15 {
println!("Mild.");
} else {
println!("Cold.");
}if age >= 13 && age <= 19 {
println!("teenager");
}
if !(day == "Sat" || day == "Sun") {
println!("workday");
}let label = if score >= 50 { "pass" } else { "fail" };let day = 6;
let kind = match day {
1..=5 => "weekday",
6 | 7 => "weekend",
_ => "not a day",
};let advice = match temp {
t if t < 0 => "freezing",
0..=15 => "cool",
_ => "warm",
};12jacket2024leap