Hi,
I’m trying to understand how I should be handling zig memory. My experience comes predominantly from garbage collected languages.
Looking at the ziglings, documentation etc. it seems if you’re creating library code you don’t specify allocators in your code, but rather, expose a parameter into your API which accepts an allocator. This enables users to choose what allocation strategy they want to use.
While I understand this choice as a way to ensure no assumptions are being made by the language, it seems strange to me that a data structure wouldn’t be in charge of figuring out the best memory allocation strategy for itself. However, that’s probably a larger topic to get into once I understand more.
When it comes to functions in my own code, say I have a function which needs to return a list of items. That list is not something I know the size of at compile time and as such I’m creating it on the heap. Since I want to return the list to the caller, should the caller be responsible for providing an allocator to my function? Is it more idiomatic zig to provide in / out parameters or to have return values?
Option 1
fn getList(allocator: std.mem.Allocator) anyerror!std.ArrayList([]u8) {
var myList = std.ArrayList([]u8).init(allocator);
// Add stuff to the list
return myList;
}
Option 2 (I presume this works?)
fn getList(list: std.ArrayList([]u8)) void {
// Add to the list
}
Option 3
Likely I’ve completely got things wrong and option 3 is the best option, if so, what should it look like?
Follow on question
If a caller is responsible for providing the allocators, and you don’t know how a caller is going to use your function / library, should you accept multiple allocators for each thing you want to return in order to keep things as flexible as possible?
Say I have a struct with two functions, each function gets called but one function maybe gets called very frequently and the memory needs freeing more frequently. Should I avoid a single allocator so it gives the caller the option to provide an allocator for each case and handle freeing them independently?