Retornando erros de funções
Torne a possibilidade de falha explícita nas assinaturas.
Retornando erros de funções é 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.
Failure in the Signature
When a function can fail, say so in its return type. An error union like ParseError!u32 warns every caller up front.
fn parse(s: []const u8) ParseError!u32 {
// ...
}Return the Success Value
On the happy path you just return the payload as normal. Zig wraps that plain value into the success side of the union for you.
return 42;Return an Error Instead
To fail, return one of your errors in the same spot. The single return statement decides which side of the union you produce.
if (s.len == 0) return error.Empty;One Return, Two Outcomes
A function with an error union can return a value in one branch and an error in another. Both satisfy the declared type.
if (ok) return value;
return error.Failed;Void Plus Errors
A function that does work but yields no value can still fail. Use !void so it returns nothing on success or an error on failure.
fn save() !void {
// ...
}Errors Bubble at the Call Site
When you call a fallible function, you receive an error union too. You cannot ignore it; the compiler makes you handle it.
const n = parse(input);Capture Errors with if
An if can split the union: capture the value in the main branch and the error after else, naming each with a pipe.
if (parse(input)) |n| {
use(n);
} else |err| {
report(err);
}Name the Error Set Precisely
Listing the exact set before ! keeps your contract honest. Callers learn the full list of failures without reading the body.
fn open(p: []const u8) FileError!File {}Errors Cross Function Boundaries
An error returned deep inside your code travels outward only when each function in the chain declares it can fail too.
Make Failure Explicit
This is the heart of Zig error handling: failure is never hidden. The signature is a promise about what can go wrong.
Compiler Has Your Back
Forget to handle a returned error and the build fails. Zig refuses to let a possible failure silently slip through.
Quick Check
A function does work but returns no useful value, yet it might fail. What return type fits?
Recap
You declared fallible functions with !T, returned values or errors from one return, and saw the compiler force callers to handle them. ✅
Perguntas Frequentes
A aula “Retornando erros de funções” é grátis?
Sim — o texto completo de “Retornando erros de funções” é 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 “Retornando erros de funções”?
Torne a possibilidade de falha explícita nas assinaturas. 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 “Retornando erros de funções”?
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
- Conjuntos de erros e a união !T
- Retornando erros de funções
- Propagando falhas com try
- Conjuntos de erros inferidos