if and else
| Expressions | |
| Chains | |
| Nesting vs guards | |
| Prefer match preview |
Expressions
An if block returns a value when both branches produce the same type. Assign the whole if expression directly to a binding:
let n = 7;
let label = if n > 5 {
"big"
} else {
"small"
};
Chains
Chain else if to test several ranges in order. Only the first true branch runs, so order from narrow to wide:
let score = 85;
let grade = if score >= 90 {
"A"
} else if score >= 60 {
"B"
} else {
"C"
};
Nesting vs guards
Deep nesting hides the main path under many levels. Return early on bad input so the main logic stays flat:
fn check(age: u32) -> &str {
if age < 18 {
return "young";
}
"adult"
}
Prefer match preview
When branches test the same value against many patterns, match reads cleaner than long else if chains. The next lesson covers it in full:
let n = 2;
let text = match n {
1 => "one",
_ => "other",
};
Next: match
Article author: Arthur Isaev