Zig, lesson 7
Programs rarely work with one value at a time. Zig's collections come in two flavours: fixed-size
arrays that need no extra memory, and growable containers like ArrayList and HashMap, which
ask you for an allocator because they need memory while the program runs.
An array's length is part of its type and never changes. A slice, like tail, is a view into
an array: a pointer plus a length, written []const i64. Functions usually take slices, so they
work with arrays of any size. Indexing past the end stops the program with an "index out of
bounds" error instead of reading random memory.
A for loop walks over a slice. Add a second range 0.. to get the index too:
2 exercises to try what you just read.
std.mem has helpers for slices, such as std.mem.min(i64, &scores) and
std.mem.max(i64, &scores). The & turns the array into a slice.
Zig never allocates memory behind your back. Anything that grows takes an std.mem.Allocator
argument, and you choose which one. In this course you will use the arena that main
receives:
An arena hands out memory and frees all of it at once when the program ends, so you don't need to
free individual pieces. Bigger programs pick allocators more carefully and free memory with
defer, but an arena is a perfect fit for short programs.
ArrayList: a growable list.empty starts an empty list. append may need more memory, so it takes the allocator and can
fail, hence the try. The current contents are always available as the slice prices.items.
StringHashMap: counting by nameA hash map stores values under keys. std.StringHashMap(V) uses strings as keys:
When you are certain a key exists, stock.get("apple").? unwraps the optional directly; if it
were null after all, the program would stop with an error. stock.count() tells you how many
keys the map holds.
For counting, getOrPut finds a key or makes room for it, telling you which happened:
The map stores the key slice, not the letters. A line read from stdin lives in the reader's
buffer and will be overwritten by the next read, so arena.dupe makes a lasting copy. key_ptr
and value_ptr are pointers; .* reads or writes what they point to.
A hash map has no useful order. To print keys alphabetically, collect them into an ArrayList
with counts.keyIterator() and sort them with std.mem.sort, giving it a function that compares
two strings with std.mem.lessThan.
std.mem.tokenizeScalar(u8, line, ' ') returns an iterator over the pieces between spaces,
skipping empty ones. Call .next() in a while loop until it returns null.
Read a line of game scores separated by spaces and print four statistics.
Input: one line with at least one whole number. Output:
That is for the input 12 6 21 3. The starter already splits the line and collects the numbers in
an ArrayList.
A class votes for the name of its pet fish. Count the votes for each name.
Input: the first line is the number of votes N (0 or more). Then N lines follow, each with
one name (a single word).
Output: one line per name, name: votes, sorted alphabetically by name. If there are no
votes, print No votes.
prints
const scores = [_]i64{ 72, 95, 88 }; // [_] lets Zig count the items: an array of 3 i64
const first = scores[0]; // 72
const n = scores.len; // 3
const tail = scores[1..]; // a slice: 95, 88for (scores, 0..) |s, i| {
try out.print("{d}: {d}\n", .{ i, s });
}const arena = init.arena.allocator();var prices: std.ArrayList(i64) = .empty;
try prices.append(arena, 12);
try prices.append(arena, 7);
// prices.items is a normal slice: { 12, 7 }
try out.print("{d} items\n", .{prices.items.len});var stock = std.StringHashMap(u32).init(arena);
try stock.put("apple", 3);
const apples = stock.get("apple") orelse 0; // get returns an optionalconst entry = try counts.getOrPut(name);
if (!entry.found_existing) {
entry.key_ptr.* = try arena.dupe(u8, name); // keep our own copy of the text
entry.value_ptr.* = 0;
}
entry.value_ptr.* += 1;Count: 4
Min: 3
Max: 21
Sum: 424
Bubbles
Finn
Bubbles
NemoBubbles: 2
Finn: 1
Nemo: 1