Typed indexes in Zig
Typed indexes in Zig help prevent mixing up indexes for different arrays. This is especially important in scenarios like spreadsheets, where row and column indexes can easily be confused. The examples provided do not fully illustrate how to enforce safety at call sites.
To make good use of this pattern, a getter helper is required. This can be a method on the array type or the index type. In a struct of arrays, having one typed index per slice is valuable.
By using typed indexes, compile time checking of field access is enforced, preventing bugs from mixing up indexes. For instance, in a spreadsheet, row and column indexes are different and should not be mixed up.
The design uses an enum to reference all struct fields for which typed indexes will be constructed. This ensures that field names match the corresponding field names in the struct. A typed index is then defined for each field, matching the index kind.
A generic function at compile time constructs these typed indexes. This function returns a type at compile time, bound to the field type at compile time. This allows for comptime knowledge of the index type.
The Sheet.Index(.row) syntax provides a nice way to call methods, feeling like a qualified concrete type. However, there are still potential bugs. For example, a Sheet.Index(.row) could be forged from any integer.
To mitigate this, Zig discourages direct field access and recommends using Sheet.at(). Proactive inspection of types is crucial when using these public methods in Zig code.
Rewritten by urgent.news; may contain errors — check the original.
Source: lvignoli.eu