The named integer or Newtype Index pattern prevents mixing up indexes on different arrays.
The above examples were not particularly illuminating to me. Andrew’s example don’t show much of how to enforce the safety at call site: any caller could call @backingInt (it used to be @intFromEnum) to recover a numerical index and pass it to the wrong array, or access array elements with a plain integer. And matklad’s one focus on building a tree data structure in a neat way, but that’s a totally different challenge that the introductory problem of mixing array indexes, so it was not a super convincing illustration for me. (Related: How to generate text: using different decoding methods ...)
In practice, to make good use of the pattern, a getter helper is required as the conventional way of accessing elements of the array. It can be a method on the array type—or the index type. (Related: Few-shot learning in practice: GPT-Neo and the 🤗 Accele...)
In a struct of array data structure, it is particularly valuable to have one typed index per slice rather than relying on careful naming.
Consider this spreadsheet example where it’s easy to mix up indexes:.
We can prevent such bug by enforcing compile time checking of field access with typed indexes.
Its clumsy to keep one index type and one accessor per field. We can use a bit of comptime to streamline the pattern, and make the recipe more generic to fit arbitrary structs. Here is a complete example.
Our spreadsheet has now several fields: a title, and row and column properties. When iterating over them, we have two kinds of indexes: row indexes and column indexes. Adding typed indexes is attractive to prevent callers from mixing them up.
It has been revealed that this enum gives us a way of referencing all the struct fields for which we will construct a typed indexed. If all fields were to be indexed, we would have used std.meta.FieldEnum(Sheet), but our spreadsheet has a title.
In a recent development, this checks at compile time that each Field enum variant name is indeed a field inside Sheet. As we’ll see later, we will have to access Sheet’s fields by name, so it’s good to check the names of Field variants match the names of Sheet fields.
This defines the kind of type indexes we’ll construct: one for row data slices and one for columns data slices. Each indexed field of Sheet has one correct typed index kind. We match them with an exhaustive switch over Field.
According to recent reports, we now have all we need to construct the two typed indexes of kinds .row and .col. A generic function returning a type at comptime is how to do it.
Sources indicate that the typed index type for row is Sheet.Index(.row), and for colum it is Sheet.Index(.col). Note the title case of the Index function, matching Zig’s convention for types.
Remains to give a way of making use of these types.
Industry observers note that this part may look complex if you are not familiar with comptime-enabled generics in Zig, so let’s be precise. This defines a method on Sheet that requires f to be a Field instance known at compile time. This allow to infer at compile time both the type of i and the return type.
Index(kindOf(f)) is just a chain of function calls on a known value. So it is comptime known. And most importantly, the type of i is bound to the one of f at compile time. Given the body of Sheet.kindOf, it’s easy to see that s.at(.row_width, i) will compile only if i has type Index(.row)!
The return type of Zig function must be comptime known, and it is the case here by using some reflection. @FieldType(Sheet, name) returns the type of the field of Sheet named name (given as a []const u8). @tagName(f) gives just that for the input enum variant. std.meta.Elem returns the element type for a collection type (here a slice). Finally, we return a pointer to allow the caller to mutate, but a value would work just fine for a read-only case.
This gives us a clear usage at call site.
The Sheet.Index(.row) syntax is particularly lovely: a method call feeling like a qualified concrete type.
Still, as I hinted earlier, this design it not completely hermetic to bugs. Nothing prevents you from forging a Sheet.Index(.row) from any integer with @fromBackingInt. And opaque types are really just for interaction with C.
Also, any caller can access Sheet fields directly (Zig has no notion of private fields.).
As for all Zig code, one must follow documented usage (“Direct access is discouraged. Use Sheet.at.”) and make good use of the public methods by proactively inspecting types.