Desempacotando com segurança com if e orelse
Lide com null sem surpresas.
Desempacotando com segurança com if e orelse é uma aula grátis de Zig Academy 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 Zig Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Zig Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
You Must Unwrap First
An optional is not the value inside it. Before you can use the contents you have to unwrap it and deal with the null case.
Capture with if
An if on an optional can bind the inner value with a pipe capture. The body runs only when the optional is not null.
if (maybe) |value| {
use(value);
}Handle the null Branch
Add an else to react when the optional is null. Now both outcomes are covered with no chance of a missing case.
if (maybe) |v| {
use(v);
} else {
handleEmpty();
}The Capture Is Unwrapped
Inside the if body the captured name is the plain inner type, not an optional. The question mark is already gone for you.
if (age) |a| {
// a is i32, not ?i32
}orelse Supplies a Default
The orelse operator unwraps an optional, but if it is null it gives back the value on its right instead.
const a = age orelse 0;orelse Is an Expression
Because orelse returns a value, you can use it inline anywhere, like passing a defaulted number straight into a function call.
print(level orelse 1);orelse Can Run Code
The right side of orelse may be a block. Use it to compute a fallback or even return early from the current function.
const v = lookup() orelse return;Force Unwrap with .?
Writing .? asserts the optional is not null and hands back the value. If it is null in a safe build, your program panics.
const a = age.?;Use .? Only When Certain
Reach for .? only when null is truly impossible. Otherwise prefer if or orelse so an empty value never crashes you.
Choose by Intent
Use if to branch on presence, orelse for a quick default, and .? only when you can prove the value is there.
Safety Is the Default
Each tool forces you to acknowledge null. That is why Zig optionals rarely turn into the surprise crashes seen in other languages.
Quick Check
You want a default of 0 when an optional integer is null. Which fits best?
Recap
You can unwrap optionals with if captures, supply defaults via orelse, or assert with .?. Each one makes you face null on purpose. ✅
Perguntas Frequentes
A aula “Desempacotando com segurança com if e orelse” é grátis?
Sim — o texto completo de “Desempacotando com segurança com if e orelse” é 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 Zig Academy, atualize para CoddyKit PRO. O curso de Zig Academy inclui 4 aulas no total.
O que vou aprender em “Desempacotando com segurança com if e orelse”?
Lide com null sem surpresas. Você pratica Zig Academy 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 Zig Academy?
Nenhuma experiência prévia é necessária. Zig Academy 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 “Desempacotando com segurança com if e orelse”?
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 Zig Academy?
Sim. Cada aula de Zig Academy 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
- Declarando tipos opcionais
- Desempacotando com segurança com if e orelse
- Ponteiros opcionais e ?*T
- null versus undefined