Declarar tipos optional
Añada ? para permitir la ausencia de un valor.
Declarar tipos optional es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 1 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.
Sometimes There Is Nothing
Real programs hit cases where a value is simply absent: a lookup misses, a field is empty. Zig models this absence safely and on purpose.
The Optional Type
An optional type can hold either a real value of some type, or the special value null meaning nothing is there.
Add a Leading Question Mark
You make any type optional by writing ? in front of it. So ?i32 is an integer that might also be null.
var age: ?i32 = null;A Value Fits Right In
An optional happily holds a normal value too. You assign 42 to an ?i32 exactly as you would assign to a plain i32.
var age: ?i32 = 42;null Is the Empty State
The keyword null is the literal that means there is no value. Only optional types are allowed to hold it.
const missing: ?u8 = null;Non-Optionals Reject null
A plain i32 can never be null. The compiler stops you, so absence stays visible in the type rather than hiding as a bad value.
var n: i32 = null; // error: expected i32Wrap Any Type You Like
Optionals are not just for numbers. You can mark a bool, a struct, a slice, or any type as optional by adding the question mark.
var found: ?bool = null;Inference Still Works
Assign an optional value and Zig infers the optional type for you, so you do not always have to spell it out by hand.
const score: ?u32 = 10;Why Not Use a Sentinel
In C people fake absence with values like -1 or a null pointer. Zig gives you a real optional so absence cannot be confused with data.
Absence Is Part of the Type
Because ? lives in the type itself, anyone reading your code instantly sees that a value might be missing and must be handled.
Defaulting to null
It is common to start an optional at null and fill it in later once you actually have the value to store.
var result: ?[]const u8 = null;Quick Check
How do you declare a u32 that might be missing?
Recap
You met optionals: write ? before a type to allow a real value or null. Absence now lives in the type, plain and visible. ❓
Preguntas frecuentes
¿La lección «Declarar tipos optional» es gratis?
Sí — el texto completo de «Declarar tipos optional» 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 «Declarar tipos optional»?
Añada ? para permitir la ausencia de un valor. 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 1 de 4.
¿Cuánto tiempo toma la lección «Declarar tipos optional»?
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
- Declarar tipos optional
- Desenvolver de forma segura con if y orelse
- Punteros optional y ?*T
- null frente a undefined