ArrayList and allocator: updating code to 0.15

Hi. I’m updating to 0.15 some code I wrote for 0.12. I’ve notice that the interface for ArrayList has changed, no keeping the reference for the allocator, and requiring it to be passed when appending data, like the below example. What was the motivation behind this change? Thanks for helping me to understand the evolution of Zig.

pub fn build_query(allocator: std.mem.Allocator, params: []Param) ![]u8 {        
    var response = try std.ArrayList(u8).initCapacity(allocator, 64);            
    for (params) |param| {                                                       
        if (response.items.len > 0) {                                            
            try response.append(allocator, '&');                                 
        }                                                                        
        try response.appendSlice(allocator, param.name);                         
        try response.append(allocator, '=');                                     
        try response.appendSlice(allocator, param.value);                        
    }                                                                            
    return response.toOwnedSlice(allocator);                                     
} 
3 Likes

To clarify, the actual change was what used to be ArrayListUnmanaged is now ArrayList. The old ArrayList is now std.array_list.Managed which will be removed in the future.

the motivations are quite simple

  • the struct is now smaller, ideal if you store them in fields.
  • the allocator is likely already available to your code, or making it available should be easy
  • it is more explicit, you can more easily tell what functions allocate and vice versa.
  • a single implementation is better for maintenance
  • you can statically initialise with .initBuf()
  • ArrayListUnmanaged was already preferred for the above reasons.
6 Likes

Hello! Oh boy, that’s quite a road you have ahead of you. One suggestion for you, take it or leave it… do the updates one at a time. I.e. update to 0.13. Then 0.14. Then 0.15. I suspect each smaller upgrade will be easier, plus you can reference the release notes for each one. And sometimes zig fmt will simply do the upgrade for you automatically (but we delete that code after 2 versions).

7 Likes

This is the only motivation I upgrade to 0.15 for developing memory intensive application.

1 Like

You didn’t have to update to get that, just had to use ArrayListUnmanaged.

6 Likes

I really appreciate your answers. I’m taking the advice. So glad to be part of this community!

3 Likes

If ArrayListUnmanaged will be removed what are the option that I cloud use instead?

It will not be removed. It’s just been renamed to ArrayList.

3 Likes