Is there a simple way to return multiple values from a function, via (for example) an anonymous struct or a tuple?
(I feel like I ought to know the answer to this but I’ve been away from Zig for a while and can’t remember, or find anything),
These are the only ways I know of:
const std = @import("std");
fn arrayMultiVal() [2]u8 {
return .{ 0, 1 };
}
fn structMultiVal() struct { x: u8, y: u8 } {
return .{ .x = 0, .y = 1 };
}
pub fn main() void {
const amv = arrayMultiVal();
std.log.info("{} {}", .{ amv[0], amv[1] });
const smv = structMultiVal();
std.log.info("{} {}", .{ smv.x, smv.y });
}
3 Likes
I used this link to write the following:
const std = @import("std");
const Tuple = std.meta.Tuple;
const SomeTuple = Tuple(&.{u32, bool});
fn returnsTuple() SomeTuple {
return .{
@as(u32, 7),
@as(bool, true),
};
}
pub fn main() void {
const x = returnsTuple();
std.log.info("{}", .{x});
}
Works as expected.
3 Likes
Thanks, both - exactly what I was looking for! Both approaches look useful for different scenarios. I don’t think I can mark both as answers so I’ll mark the first one, but thanks both.
also tuple with type annotation using anonymous struct:
fn tupleMultiVal() struct { u8, bool } {
return .{ 0, true };
}
https://ziglang.org/documentation/master/#Type-Coercion-Tuples-to-Arrays
4 Likes