authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-02-05 10:28:05-05:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-02-05 10:28:56-05:00
logac4e38226b45081dfb66f006bba38b11c121ad45
tree853f48a206c6179dd8c07af1e979da027acccfb5
parent4010f6a11dafa1d047d66a637a0efe58d80a52c6
signature Commit is signed but in an unrecognized format.

docs: clarify passing aggregate types as parameters


1 files changed, 15 insertions(+), 6 deletions(-)

doc/langref.html.in+15-6
......@@ -3192,7 +3192,16 @@ fn foo() void { }
31923192 {#code_end#}
31933193 {#header_open|Pass-by-value Parameters#}
31943194 <p>
3195 In Zig, structs, unions, and enums with payloads can be passed directly to a function:
3195 Primitive types such as {#link|Integers#} and {#link|Floats#} passed as parameters
3196 are copied, and then the copy is available in the function body. This is called "passing by value".
3197 Copying a primitive type is essentially free and typically involves nothing more than
3198 setting a register.
3199 </p>
3200 <p>
3201 Structs, unions, and arrays can sometimes be more efficiently passed as a reference, since a copy
3202 could be arbitrarily expensive depending on the size. When these types are passed
3203 as parameters, Zig may choose to copy and pass by value, or pass by reference, whichever way
3204 Zig decides will be faster. This is made possible, in part, by the fact that parameters are immutable.
31963205 </p>
31973206 {#code_begin|test#}
31983207const Point = struct {
......@@ -3201,20 +3210,20 @@ const Point = struct {
32013210};
32023211
32033212fn foo(point: Point) i32 {
3213 // Here, `point` could be a reference, or a copy. The function body
3214 // can ignore the difference and treat it as a value. Be very careful
3215 // taking the address of the parameter - it should be treated as if
3216 // the address will become invalid when the function returns.
32043217 return point.x + point.y;
32053218}
32063219
32073220const assert = @import("std").debug.assert;
32083221
3209test "pass aggregate type by non-copy value to function" {
3222test "pass struct to function" {
32103223 assert(foo(Point{ .x = 1, .y = 2 }) == 3);
32113224}
32123225 {#code_end#}
32133226 <p>
3214 In this case, the value may be passed by reference, or by value, whichever way
3215 Zig decides will be faster.
3216 </p>
3217 <p>
32183227 For extern functions, Zig follows the C ABI for passing structs and unions by value.
32193228 </p>
32203229 {#header_close#}