Valores padrão dos campos
Inicialize campos sem repetição.
Valores padrão dos campos é uma aula grátis de Zig Academy no CoddyKit. Esta é a aula 3 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.
Repeating Yourself
If most instances start the same way, retyping every field is tedious. Zig lets a field carry a default value built into the type.
Give a Field a Default
Add = value after the field type. Any instance that omits that field gets the default automatically.
const Config = struct {
retries: u8 = 3,
};Omit It on Creation
Now you can build a value without mentioning the defaulted field, and it still gets 3.
const c = Config{};Override When You Want
The default is only a starting point. Set the field explicitly in the initializer to use a different value.
const c = Config{ .retries = 5 };Mix Defaults and Required
A struct can blend both. Fields with no default are required; defaulted ones may be skipped.
const User = struct {
name: []const u8,
active: bool = true,
};Empty Initializer
If every field has a default, you can construct with a bare .{} and let all defaults apply at once.
const Settings = struct {
volume: u8 = 50,
muted: bool = false,
};
const s = Settings{};Defaults Are Compile-Time
A default must be a value Zig can compute at compile time, like a literal or a comptime expression.
const Limits = struct {
max: usize = 1024,
};Any Type Can Default
Defaults work for any field type: numbers, bools, slices, even nested structs with their own defaults.
const Box = struct {
size: Settings = Settings{},
};Default to null
An optional field often defaults to null, a clean way to say it starts empty until you fill it in.
const Node = struct {
next: ?*Node = null,
};Cleaner, Safer Code
Defaults shrink your call sites and document intended starting state, so readers see the normal value right in the type.
Defaults Are Per Instance
Each new instance gets its own fresh copy of the default. They never share state between values.
Quick Check
What happens to a defaulted field you leave out?
Recap
You learned default field values: write = value after a field, then omit it to use the default or set it to override. ⚙️
Perguntas Frequentes
A aula “Valores padrão dos campos” é grátis?
Sim — o texto completo de “Valores padrão dos campos” é 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 “Valores padrão dos campos”?
Inicialize campos sem repetição. 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 3 de 4.
Quanto tempo leva a aula “Valores padrão dos campos”?
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 estruturas e campos
- Métodos e o parâmetro self
- Valores padrão dos campos
- Estruturas anônimas e tuplas