Should I pass constants by reference?

In the standard library I always see that structs are passing self like this: self: Self, not like self: *const Self, so Im wondering should I also do that for passing all structs into functions, for example i have a function that takes an immutable struct, should I pass it like value(param: Struct) or like pointer(param: *const Struct)? Also when returning from functions, should I return value or pointer to value. I dont care about lifetimes in this case, just curious in general. Is there any cost or benefit of doing either it way? It would be logical to me that I should always pass by using *const

1 Like

Hi! This should clarify the function argument passing semantics:
Note: self is just a naming convention for the “receiver” parameter. It could be different, like this, but for convenience and conformity everyone uses self.

1 Like

Im curious about which one i should default to, pass structs by value or reference for constant params, from what I read, it seems like the compiler can decide to do whats best, but is that gonna change?

Well, as you’ve noted from std lib, the commonly adopted default is to pass by value.

I found the C programmer! :slight_smile:

Zig is a little unique here, when a function takes a parameter by value, it’s free to optimize that into a reference under the hood. My general advice is to do the simplest thing, just pass and return everything by value until you can’t.

Some situations where you cant, is if you need modify the contents of Self, then you’ll need to take *Self. It’s pretty rare that you’d need to take in *const Self, but there are some situations.

There has been 1 time where I had a very large type and Zig wasn’t optimizing passing it around as a reference in Debug mode and it was causing a huge slow down that I had to force it to be a reference. In general though it’s not something to worry about.

1 Like