Chapter Summary
Enums, structs, errors, and unions are our main modeling tools in Zig.
- Enums: used to define types with a fixed set of values. You can assign ordinal values by hand, and they can have their own methods and variables.
- Structs: objects with named fields-these can hold pretty much anything, including other enums or structs. You can define methods, constants, and variables inside them. Tuples are just anonymous structs (fields with no names).
- Errors: In Zig, errors are values and are defined with error{ }. We handle them with try, catch, if |err_x|, and errdefer (similar to defer but only runs on error). Different errors can be merged with || to form a new set.
- errdefer: runs a block of code only if the function returns an error.
- Unions: lets you store one active value out of several possible types.
Two kinds:
- Bare union: doesn't track which field is active,
- Tagged union: when using union(enum) or an external enum as a tag, we can tell which field is active.