#conventions/best practices for passing allocators to functions?

1 messages · Page 1 of 1 (latest)

brittle granite
#

I'm wondering if there are common conventions that are worth knowing. e.g., is it common to always pass the allocator as the 1st function arg, etc.

sonic owl
#

typically passing the allocator first is a fine bet, although an equally frequent exception to this is when you have something like

fn foo(self: @This(), allocator: Allocator) !void {...}
#

in this case you pass the allocator second in order to be able to use method syntax

brittle granite
#

is this example a function declared within a struct? ^

sonic owl
#

ye

#

as well, a slightly less frequent but equally valid point of contention is interop with non-zig libraries: e.g., in vulkan, the convention is to pass the allocator last, and so when I was wrapping some vulkan bindings in order to pass zig allocators to vulkan functions, it was easier to also pass it as the last parameter

brittle granite
#

oh interesting

#

I would imagine (because I'm still just starting my zig journey) that passing allocators to functions is really contagious, and results in many, many functions taking in allocators

sonic owl
#

indeed, allocation is contagious

#

you can think of it like a motivator to at least think in passing "could I do this without allocation?"

brittle granite
#

is that pretty common across zig codebases, or do people employ tricks to avoid having to pass the allocator arg everywhere?

sonic owl
#

I mean, "tricks"?

#

I guess the closest you'd get is that a lot of data structures carry them as fields

brittle granite
#

well in a way passing an allocator to a struct and then just using it internally is kind of a trick right

sonic owl
#

but that's not really so much a trick as it's just compacting code

brittle granite
#

ok

#

thanks for the clarity

sonic owl
#

sure, np

#

btw

brittle granite
#

this language seems super cool so far

sonic owl
#

although this is in reference to naming conventions, I feel this is also pertinent here, from the zig language style guide:

These are general rules of thumb; if it makes sense to do something different, do what makes sense. For example, if there is an established convention such as ENOENT, follow the established convention.

#

we're not all that dogmatic

brittle granite
#

that makes sense, I just don't have the background to know established convention in the zig community yet. kind of at the heart of my question