Passing a big struct by value when having a struct pointer

I’ve been passing large structs by value when I only need read-only access in the called function. However, if such a call needs to be made when only a struct pointer is available, I have to use s.* to pass it.

I’m worried that this might make a copy, since I can’t find any doc on this case. Should I declare the param type as *const in the read-only function to guarantee that a copy is not made?

const Big = struct {
    buf: [1024]u8,
};
fn f() void {
    var big = Big{.buf = [_]u8{0} ** 1024};
    g(&big);
}
fn g(big: *Big) void {
    h(big.*); // I'm worried that this could make a copy
}
fn h(big: Big) void { // should this be `*const Big`?
}

The use case is that g needs to modify the struct, and also call h which only needs read-only access. h is called from other read-only functions, not just from g. All functions are normal zig functions, not extern.

While I am sure that there is going to be no copy on .* unless the result location demands it,
I would suggest not to rely on parameter reference optimization too much, since it is going to be applied only to pure functions in the future and even right now sometimes there still are some surprising copies.

So I would suggest: Always pass by const reference, if you know that the struct is really big.

4 Likes

Thank you! Good to know.