Chapter Summary
Generics in Zig let you write functions and structs that accept different data types. The compiler uses these definitions as templates to generate specialized code at compile time.
- Builtin functions like @TypeOf, @typeInfo, @hasField, and @typeName let us inspect types at compile time and generate code based on what they detect about the data.
- @compileError can force a compile-time error so that if certain conditions aren’t met, compilation will be stopped.
- Anonymous and encapsulated functions are defined within temporary structs, allowing us to isolate helper logic without polluting the broader scope.
- We build types from other types at compile time using generic structs. These are created based on the parameters received in a generic function that returns a type.
- @This refers to the current type from within one of its methods - very useful when composing generic structs
- anyopaque is used with pointers to unknown (erased) types, allowing us to work with data of different kinds.
- @ptrCast and @alignCast help us get back the type that was erased.