// DOCS NAVIGATION
if let_
SOURCE: content/docs/reference/04-avancado.md — 04 Avançado / 2. if let
PT-BR:
if let é um atalho para aplicar um único padrão de correspondência. É especialmente útil para desestruturar Option e Result sem escrever um match completo.
EN-US:
if let is a shortcut for applying a single pattern match. It is especially useful for destructuring Option and Result without writing a full match.
Sintaxe / Syntax
if let Padrão = expressão {
// executado quando o padrão corresponde / executed when pattern matches
} else {
// executado quando não corresponde / executed when it doesn't match
}
Exemplos com Option / Examples with Option
module if_let_demo
from std.io import println
public func main() {
let talvez: Option<int> = Option::Some(42)
let nada: Option<int> = Option::None
// Desestruturando Some / Destructuring Some
if let Option::Some(valor) = talvez {
println(f"Tenho um valor: {valor}")
// "Tenho um valor: 42"
} else {
println("Nenhum valor")
}
// Se for None, cai no else / If None, falls to else
if let Option::Some(v) = nada {
println(f"Valor: {v}")
} else {
println("Sem valor")
// Imprime isso / Prints this
}
}
Exemplos com Result / Examples with Result
let resultado: Result<int, string> = Result::Ok(100)
let erro: Result<int, string> = Result::Err("não encontrado")
if let Result::Ok(valor) = resultado {
println(f"Sucesso: {valor}")
// "Sucesso: 100"
}
if let Result::Err(msg) = erro {
println(f"Erro: {msg}")
// "Erro: não encontrado"
}
Exemplos com Enums Customizados / Custom Enum Examples
enum Forma {
Circulo { raio: float },
Retangulo { largura: float, altura: float },
Ponto
}
func processar(f: Forma) {
if let Forma::Circulo { raio } = f {
println(f"É um círculo com raio {raio}")
} else {
println("Não é um círculo")
}
}
if let Encadeados / Chained if let
func obter_nome_usuario(id: int) returns Option<string> {
if id == 1 {
return Option::Some("Alice")
}
return Option::None
}
func obter_email(nome: string) returns Option<string> {
if nome == "Alice" {
return Option::Some("alice@exemplo.com")
}
return Option::None
}
public func main() {
let id = 1
if let Option::Some(nome) = obter_nome_usuario(id) {
if let Option::Some(email) = obter_email(nome) {
println(f"Email do usuário: {email}")
} else {
println("Usuário sem email")
}
} else {
println("Usuário não encontrado")
}
}