0Pricing
Zig Academy · Lección

Unions que contienen uno de varios tipos

Almacene formas alternativas en un mismo espacio.

Unions que contienen uno de varios tipos es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Zig Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Zig Academy incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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 active

A 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. 🔀

Preguntas frecuentes

¿La lección «Unions que contienen uno de varios tipos» es gratis?

Sí — el texto completo de «Unions que contienen uno de varios tipos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Zig Academy, actualiza a CoddyKit PRO. El curso de Zig Academy incluye 4 lecciones en total.

¿Qué aprenderé en «Unions que contienen uno de varios tipos»?

Almacene formas alternativas en un mismo espacio. Practicas Zig Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Zig Academy?

No se requiere experiencia previa. Zig Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Unions que contienen uno de varios tipos»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Zig Academy?

Sí. Cada lección de Zig Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Enums para un conjunto fijo de valores
  2. Unions que contienen uno de varios tipos
  3. Unions etiquetadas y switch
  4. Métodos de enums y enteros subyacentes
← Volver a Zig Academy