Chapter summary
To declare a function: fn followed by the function name, then parentheses with or without typed parameters, and always specify the return type, even if it is void (returns nothing).
- Function parameters in Zig are always immutable and passed by copy, even pointers.
- A function can return several values at once, using arrays, tuples (anonymous structs).
- We can extract returned values using destructuring.
- To indicate an optional value (may be null), use ?T. The orelse lets us fall back to a default value.
- Inline functions allow the compiler to insert the function body directly at the call site.
- Code can be organized into libraries. Functions and types are imported with @import and must be marked with pub to be accessible from outside.
- Dynamic lists (ArrayLists) allow working with collections that can grow or shrink at runtime, unlike fixed-size arrays.
- Since errors in Zig are values, functions can return them using !T or error{NameError,...}!T, and they are handled with try or catch.