Zig Parameters
A parameter is a named value a function receives when it is called. Parameters let the same function work on different values each time.
Pass one value in
The double function receives one i32 named n. Calling it with 6 sends back twice that value.
const std = @import("std");
fn double(n: i32) i32 {
return n * 2;
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d}\n", .{double(6)});
}Use two parameters
The add function takes two values, a and b. The call passes 4 and 5, in that order.
const std = @import("std");
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d}\n", .{add(4, 5)});
}Same function, different arguments
One function can serve many calls. Each call passes its own value and gets its own result.
const std = @import("std");
fn triple(n: i32) i32 {
return n * 3;
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d} {d}\n", .{ triple(2), triple(5) });
}Example
const std = @import("std");
fn lineTotal(unit_price: i32, quantity: i32) i32 {
return unit_price * quantity;
}
pub fn main() !void {
const out = std.io.getStdOut().writer();
const first = lineTotal(3, 4);
const second = lineTotal(5, 2);
try out.print("{d}\n", .{first + second});
}Key points
- Parameter: a named input written inside the function's parentheses, with its type.
- Argument: the actual value passed for a parameter at a call.
- Type: every parameter declares a type, such as n: i32, and the argument must fit that type.
- Return value: a function can use its parameters to work out the value it sends back.
- Multiple parameters: two or more parameters are separated by commas and matched to arguments in order.
In this example, lineTotal multiplies a unit price by a quantity and returns the result. The first call passes 3 and 4, so first holds 12. The second call passes 5 and 2, so second holds 10, and main prints their sum, 22.
Note
a parameter cannot be changed inside its function, so copy it into a var first if the value must change.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A function starts with `fn subtract(a: i32, b: i32) i32` and returns a - b. What does subtract(10, 4) return?