Returning multiple values
We can return more than one value at once from a function in two ways:
- By returning an array if the values are of the same type
- By using anonymous structs
In the following example, we are tasked with building a mechanism to carry water from the river up to the castle, which is 90 meters high! As the best Renaissance engineer at court, we devise a tower that, thanks to an ingenious system of oscillating buckets, is capable of lifting water up to 4.5 meters high:
hydrotower.zig |
|
const std = @import("std"); const print = std.debug.print; // a tower with oscillating buckets const HydroTower = struct { // typical percentage of water that can be // carried per meter of height gained const N_EFFICIENCY_PER_METER: f32 = 0.98; // tower height n_height: f32, n_efficiency_per_meter: ?f32, // optional // the tower lifts the incoming water // and returns how much arrives and at what height fn lift_water(self: *const HydroTower, n_input: f32) [2]f32 { return .{ n_input * std.math.pow( f32, // if we do not set a specific efficiency // for the tower, the typical one is used self.n_efficiency_per_meter orelse HydroTower.N_EFFICIENCY_PER_METER, self.n_height, ), self.n_height, }; } }; // river flow carried to the tower const WaterFlow = struct { n_liters_per_second: f32, }; pub fn main() void { print("~\n", .{}); // flow of 2L per second const o_river = WaterFlow{ .n_liters_per_second = 2 }; // tower built with a height of 4.5m const o_tower = HydroTower{ .n_height = 4.5, // no specific efficiency is set .n_efficiency_per_meter = null, }; // destructure the returned array const n_water, const n_height = o_tower .lift_water(o_river.n_liters_per_second); print("{}L → {}L at {}m \n", .{ o_river.n_liters_per_second, n_water, n_height }); } |
|
$ zig run hydrotower.zig |
|
~ 2L → 1.826196L at 4.5m |
The lift_water method returns multiple values using an array:
|
[2]f32 { // <- it will return an array with 2 float elements
//... // destructure the returned array const n_water, const n_height = o_tower .lift_water(o_river.n_liters_per_second); |