How does arraylist initCapacity work?

I am reading Aarraylist source code and doing zig.guide. I have written this code:

test "arraylist arena initCapacity" {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var list = ArrayList(u8).initCapacity(allocator, 4);

    try list.append('H');
    try list.append('E');
    try list.append('L');
    try list.append('L');

    try expect(eql(u8, list.items, "HELL"));
}

and and I can not append. why?

You forgot a try:

var list = try ArrayList(u8).initCapacity(allocator, 4);
2 Likes

Ok i am stupid. thank you!

2 Likes

You’re welcome, no worries!

Btw, you can also use a special function for testing string equality:

try std.testing.expectEqualStrings(list.items, "HELL");
3 Likes

thanks for the tip!

2 Likes

No, don’t blame yourself.
When the compiler displays that message for the missing try, it’s a compiler problem.

test.zig:10:13: error: no field or member function named 'append' in 'error{OutOfMemory}!array_list.ArrayListAligned(u8,null)'
    try list.append('H');
        ~~~~^~~~~~~
3 Likes