Destructuring

for Zig 0.15.2 Buy

Destructuring

An interesting point in the example is the destructuring of the result.

This destructuring can be done without it coming from a function, as long as it is applied to tuples, arrays, and vectors. Vectors are a type we will see later.

We could use a tuple (an anonymous struct is a tuple) instead of an array to return multiple values - this is very useful when those values are of different types:

  // it will return a tuple

  fn lift_water(self: *const HydroTower, n_input: f32) struct { f32, u8 } {

  //...

  // destructure the returned tuple

  const f_water, const n_height = o_tower

      .lift_water(o_river.n_liters_per_second);

  // or we retrieve the tuple to destructure it or use it later

  const t_resp = o_tower.lift_water(o_river.n_liters_per_second);

  // destructure

  const f_water, const n_height = t_resp;

  // directly use the values by index

  t_resp[0], t_resp[1]

We can also use an anonymous struct with named fields, but we will not be able to destructure it:

  // it will return an anonymous struct with named fields

  fn lift_water(self: *const HydroTower, n_input: f32)

     struct { f_water: f32, n_height: u8 } {

  //...

  // cannot destructure the struct with named fields

  const o_output = o_tower

      .lift_water(o_river.n_liters_per_second);

  // in this case we access the values by name

  print("{}L at {}m  \n", .{ o_output.f_water, o_output.n_height });

Because even though every tuple is an anonymous struct, not all anonymous structs are tuples. If we use named fields, it is no longer a tuple.

Returning multiple values
Optional values
© 2025 - 2026 Zen of Zig