Uniões que armazenam um entre vários tipos
Armazene formas alternativas em um único espaço.
Uniões que armazenam um entre vários tipos é 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.
One Slot, Many Shapes
Sometimes a value could be an integer or a float, but only one at a time. A union stores exactly one of several possible types in a single slot.
Declaring a Union
You write union and list named fields, each with its own type. The value holds just one of those fields at any moment.
const Number = union { int: i64, float: f64 };It Holds One Field at a Time
Unlike a struct, a union does not keep every field at once. It stores a single active field, and the others are not present.
Setting the Active Field
You initialize a union by choosing one field with the dot syntax. That field becomes the active one for the value.
var n = Number{ .int = 42 };Reading the Active Field
You read a union through the field you set. Access n.int and you get the integer you stored, just like reaching into a struct.
const x = n.int;Memory Is Shared
A union reserves room for its largest field and reuses that space. This makes it a compact way to hold one of several variants.
Switching the Active Field
Assigning a new field makes that field the active one and the old value goes away. The union now represents a different shape.
n = Number{ .float = 3.14 };Reading the Wrong Field
If you read a field that is not active, that is a bug. In safe builds Zig detects the wrong access and triggers a panic.
const f = n.int; // wrong field activeA Bare Union Has No Tag
A plain union does not remember which field is active. You must track that yourself, which is exactly the problem a tagged union solves.
Unions vs Structs
A struct is a logical AND of its fields, all present together. A union is a logical OR: just one field lives at a time.
When to Reach for a Union
Use a union when a value naturally takes one of a few forms, like a token that is a number or a symbol, never both at once.
Quick Check
How many of a union's fields hold a value at the same time?
Recap
You met unions: one slot that holds a single field from several typed options. They share memory, so set and read only the active field. 🔀
Perguntas Frequentes
A aula “Uniões que armazenam um entre vários tipos” é grátis?
Sim — o texto completo de “Uniões que armazenam um entre vários tipos” é 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 “Uniões que armazenam um entre vários tipos”?
Armazene formas alternativas em um único espaç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 2 de 4.
Quanto tempo leva a aula “Uniões que armazenam um entre vários tipos”?
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
- Enumerações para um conjunto fixo de valores
- Uniões que armazenam um entre vários tipos
- Uniões marcadas e switch
- Métodos de enumeração e inteiros subjacentes