if let, let else and week 4 review
Sometimes a full match is too much when you only care about one case. For that there are if let and let else, shortcuts that combine pattern and condition. In this lesson you will learn them along with the most used enum in the whole standard library, Option, which represents "there may be a value or there may not". We close the week with a mini program that brings together structs, enums and match.
Option: absence as a type
Many languages have null, and its misuse is famous for causing bugs. Rust has no null. Instead, the standard library defines enum Option<T> { None, Some(T) }. A function that may find nothing returns Option, and the compiler forces you to decide what to do in the None case before using the value. It is impossible to "forget" to check. We will exploit this type in depth in week 5; for now it is enough to know how to create and consume it.
fn find_even(numbers: &[i32]) -> Option<i32> {
for &n in numbers {
if n % 2 == 0 {
return Some(n);
}
}
None
}
fn main() {
match find_even(&[3, 5, 8, 9]) {
Some(n) => println!("first even: {n}"),
None => println!("no even numbers"),
}
println!("{:?}", find_even(&[1, 3]));
}if let
if let pattern = value { ... } runs the block only if the pattern matches, and you can add an else for the rest. It is exactly a match with one arm and a wildcard, but shorter and more readable. Use it when you care about a single case. If you care about two or more, prefer match: the compiler will check that none is missing. With if let you lose that exhaustiveness check, so it is a conscious trade-off.
#[derive(Debug)]
enum Message {
Text(String),
Number(i32),
Ping,
}
fn main() {
let inbox = vec![Message::Number(7), Message::Ping, Message::Text(String::from("hi"))];
for m in &inbox {
if let Message::Text(content) = m {
println!("text: {content}");
} else {
println!("other: {:?}", m);
}
}
let maybe: Option<u32> = Some(3);
if let Some(n) = maybe {
println!("got {n}");
}
}let else and while let
let else is for "extract or leave": let Some(x) = option else { return; }; If the pattern matches, the variable is available in the rest of the function and you avoid levels of indentation; if not, the else block must end execution with return, break, continue or a panic. while let repeats while the pattern keeps matching, something very common when consuming a stack with pop(), which returns Option.
fn first_char_upper(text: &str) -> Option<char> {
let Some(c) = text.chars().next() else {
return None; // empty text
};
Some(c.to_ascii_uppercase())
}
fn main() {
println!("{:?} {:?}", first_char_upper("rust"), first_char_upper(""));
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
print!("{top} ");
}
println!();
}Week 4 review
- struct groups named fields; impl adds methods (&self, &mut self) and associated functions (new).
- enum models "one of several variants", and each variant can carry data.
- match is exhaustive; it supports guards, ranges, | and the wildcard _.
- Option<T> replaces null; if let, let else and while let are shortcuts for a single pattern.
To choose between the tools: use match when several cases matter, if let when only one matters and you want a simple else, let else when the failure branch must end the function, and while let to consume a source of values until it runs out. With practice, writing them becomes automatic and your code gains clarity.
enum Account {
Cash(f64),
Card { number: String, limit: f64 },
Empty,
}
fn available(acc: &Account) -> Option<f64> {
match acc {
Account::Cash(amount) => Some(*amount),
Account::Card { limit, .. } => Some(*limit),
Account::Empty => None,
}
}
fn main() {
let accounts = [
Account::Cash(20.5),
Account::Card { number: String::from("1234"), limit: 100.0 },
Account::Empty,
];
for acc in &accounts {
if let Some(v) = available(acc) {
println!("available: {v}");
} else {
println!("no funds");
}
}
}Проверьте себя
Вопрос 1 из 5What does Option<T> replace in Rust?
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов