0Pricing
Learn Rust Coding · Aula

if let e while let

Correspondência concisa

if let e while let é uma aula grátis de Learn Rust Coding no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Learn Rust Coding, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Learn Rust Coding inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 rest
  • let else — bind or bail out early
  • while let — loop while a pattern keeps matching
  • match — 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 let handles a single pattern, optionally with else
  • let else binds or diverges early
  • while let loops while a pattern matches
  • Switch to match when multiple cases need handling

Perguntas Frequentes

A aula “if let e while let” é grátis?

Sim — o texto completo de “if let e while let” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Learn Rust Coding, atualize para CoddyKit PRO. O curso de Learn Rust Coding inclui 4 aulas no total.

O que vou aprender em “if let e while let”?

Correspondência concisa Você pratica Learn Rust Coding com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Learn Rust Coding?

Nenhuma experiência prévia é necessária. Learn Rust Coding no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “if let e while let”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Learn Rust Coding?

Sim. Cada aula de Learn Rust Coding inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Análise aprofundada de match
  2. if let e while let
  3. Vinculação com @
  4. Desestruturação
← Voltar para Learn Rust Coding