Search code examples
structzig

Passing structs to functions and returning structs from functions in Zig


I am writing some Zig code that returns structs from functions and then passes these structs to other functions "by value" (i.e. I'm not explicitly passing a pointer) and it seems to be working, but I wonder if this is correct.

From the docs it looks like the compiler is implicitly deciding if the struct is going to be passed as an argument as a pointer or as a copy. Is this correct? So should I just pass it "by value" whenever possible and leave it up to Zig to decide what to do?

What about returning a struct from a function? Is Zig always copying in this case?


Solution

  • Yes, prefer to pass structs as values, the compiler will optimize it, unless you need to modify the original struct, in which case you'd have to pass a pointer to the struct.

    I haven't seen anything in the documentation about the compiler optimizing returned struct values, but it likely does optimizations there. Even if not, prefer to return the struct as a value, since returning a pointer would limit the usability of your functions.