How do I get the number of items in ArrayList

Getting the count of elements in an ArrayList seems to be more difficult that I would have expected :grinning:

I have seen code in the wild using .count() and len() but from this issue Add a method to return length of ArrayList 路 Issue #5669 路 ziglang/zig 路 GitHub it seems those have been deprecated in favour of using items.len

But now It seems items.len also does not exist. As my code fails to compile

error: struct 'array_list.ArrayListAligned(main.Entry,null)' has no member named 'items'

And when I check the documentation here Zig Documentation there is no mention of the items field.

So anyone knows how to get the number of items in an ArrayList? Thanks!

Sounds like something else is going on here. ArrayList has an items fields (it鈥檚 a slice).

Please post your code so we can see the surrounding context. You may be getting this as a compiler error but the issue is somewhere else.

My guess is that you鈥檙e doing something like:

const list = std.ArrayList(u32);
const len = list.items.len;

but that fails with the error in the OP because std.ArrayList returns a type, not an instance. Instead you want to do:

const list = std.ArrayList(u32).init(allocator);
defer list.deinit();

const len = list.items.len;
4 Likes

It is basically this

const Entry = struct {
    actor: []const u8,
    age: u8,
};

const entries = std.ArrayList(Entry);
entries.deinit();

while (entries.items.len > 0) {
    // pop from entries and do stuff with it
}

Also the documentation does not show that items is a field too

Yup, @squeek502 is correct. Here鈥檚 an example that I hope helps:

// this is the type of the array list
const ArrayListType = std.ArrayList(u8);

// use whatever allocator you want - this is an instance of the type
const array_list_instance = ArrayListType.init(std.heap.page_allocator);

const n = array_list_instance.items.len;
1 Like

Thanks for this. What would you say is the best way to navigate the documentation then?

Because Zig Documentation did not make it clear, that I am looking at the type and not an instance (although I would assume the type should have info about the field).

The best thing to look at would be the test cases, like this one for example:

The documentation isn鈥檛 great for generic types (i.e. functions that return a type) yet. You can click on the [src] link and look at the test blocks in the file, though.

1 Like

Here鈥檚 a relevant issue for the documentation side of things:

2 Likes

To be fair, the documentation you reference does have the words, 鈥淭ype Function鈥 at the top. For me, it has taken some time for that term to sink in and what it implies. Still, I find myself spending more time than I would like spelunking the standard library source code. But I have every confidence that it will get better.