I’m trying to learn more about std.ArrayList
. I have this test code.
test "stdArrayList" {
var a = std.ArrayList(i32).init(std.testing.allocator);
defer a.deinit();
try a.append(1);
std.debug.print("items.len: {d}\n", .{a.items.len});
std.debug.print("capacity: {d}\n", .{a.capacity});
for (a.items) |n| {
std.debug.print("{d}\n", .{n});
}
}
I was surprised when the program printed this. I thought it would print 1
, then a bunch of garbage because there are 7 unused spaces in the array.
a.items.len: 1
capacity: 8
1
But, OK. I’m guessing the for loop stops based on items.len
.
Then I tried doing a[1] = 20
and my code blew up with index out of bounds
. Which ok. I guess that makes sense, the len
is 1
.
But, now I’m confused. Where is the extra capacity stored?
I decided to try to read ArrayList | Zig Documentation. But, it’s kinda long and I’m very new to Zig…
From what I could gather, it seems like ArrayList
does some funny business with items
that I don’t quite understand.
I think I found where the extra capacity is stored, but I don’t quite understand how it works…
/// Returns a slice of all the items plus the extra capacity, whose memory
/// contents are `undefined`.
pub fn allocatedSlice(self: Self) Slice {
// `items.len` is the length, not the capacity.
return self.items.ptr[0..self.capacity];
}
I think I need to learn more about slices… is it possible to mess with the slice internals?