Hacker News new | ask | show | jobs
by jenadine 1204 days ago
So you have coloured functions? The red that can allocate, and the blue that cannot?
4 comments

It's not quite as clear-cut, some stdlib modules take an allocator when an 'object' is created (containers mostly work like this), others on each function call that needs to allocate (but crucially, one way or another, an allocator needs to be passed in).

In any case it's not nearly as limiting as the 'red-blue' async-await color split in other languages, and I can't think of a single downside of explicitly passing allocators into stdlib modules instead of having a hidden global allocator.

The approach to always pass allocators isn't all that Zig specific either, it's also a good library design practice in pretty much all other languages which allow explicit memory management.

No, I wouldn't describe it like that. It's more that there isn't an ambient, implicit Allocator lying around for stdlib to use. It is explicitly provided by callers.
If you want to think of it that way, the stdlib `voluntarily` colors its functions by allocator. You can do whatever you want in your own functions, including always using a global allocator and never passing it anywhere.
Well, you have expicit allocators. A popular branch of the field calls this ‘dependency injection’. It's true that the current standard library never allocates implicitly, because that would be bad on constrained projects, but there's nothing stopping you from writing code that does so, or presumably even using libc.