if let y while let
Matching conciso
if let y while let es una lección gratuita de Learn Rust Coding en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Learn Rust Coding, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Learn Rust Coding incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Concise Matching
Sometimes you care about just one pattern. if let and while let give you concise matching without a full match.
The if let Form
if let runs a block only when a value matches a pattern, binding any captured data.
fn main() {
let maybe = Some(10);
if let Some(n) = maybe {
println!("value is {n}");
}
}if let vs match
if let is sugar for a match with one interesting arm and a _ => () fallthrough. Use it when the other cases need no handling.
fn main() {
let config: Option<i32> = None;
// match equivalent would have an empty _ arm
if let Some(v) = config {
println!("configured: {v}");
}
println!("done");
}Adding an else
Attach an else to handle the non-matching case.
fn main() {
let result: Result<i32, String> = Err("boom".to_string());
if let Ok(v) = result {
println!("ok: {v}");
} else {
println!("failed");
}
}let else
let ... else binds when the pattern matches, otherwise runs a diverging block (like return). Great for early exits.
fn parse(s: &str) -> i32 {
let Ok(n) = s.parse::<i32>() else {
println!("not a number");
return 0;
};
n * 2
}
fn main() {
println!("{}", parse("21"));
println!("{}", parse("oops"));
}The while let Form
while let keeps looping as long as a value matches a pattern. It's perfect for draining things like stacks.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}Looping Over Iterators
while let can iterate by repeatedly calling next, stopping when it returns None.
fn main() {
let mut iter = [10, 20, 30].into_iter();
while let Some(x) = iter.next() {
println!("{x}");
}
}Guards with if let
Combine a guard by adding an && condition (Rust 2024) or nesting an if inside.
fn main() {
let value = Some(8);
if let Some(n) = value {
if n > 5 {
println!("big: {n}");
}
}
}When to Use Which
Guidelines:
if let— handle one pattern, ignore the restlet else— bind or bail out earlywhile let— loop while a pattern keeps matchingmatch— when you need to handle multiple cases
Readability Tradeoff
These forms reduce boilerplate but can hide cases. If you find yourself handling several patterns, switch back to a full match for clarity.
Nesting if let
You can chain optional values by nesting if let, unwrapping one layer at a time.
fn main() {
let outer: Option<Option<i32>> = Some(Some(99));
if let Some(inner) = outer {
if let Some(value) = inner {
println!("value is {value}");
}
}
}Quick Check
Which construct repeatedly runs a loop body while a value keeps matching a pattern?
Recap
You learned concise matching:
if lethandles a single pattern, optionally withelselet elsebinds or diverges earlywhile letloops while a pattern matches- Switch to
matchwhen multiple cases need handling
Preguntas frecuentes
¿La lección «if let y while let» es gratis?
Sí — el texto completo de «if let y while let» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Learn Rust Coding, actualiza a CoddyKit PRO. El curso de Learn Rust Coding incluye 4 lecciones en total.
¿Qué aprenderé en «if let y while let»?
Matching conciso Practicas Learn Rust Coding con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Learn Rust Coding?
No se requiere experiencia previa. Learn Rust Coding en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «if let y while let»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Learn Rust Coding?
Sí. Cada lección de Learn Rust Coding incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Análisis avanzado de match
- if let y while let
- Binding con @
- Desestructuración