How do I make an array of tuples? I have a function that takes an arbitrary function and calls it on every element of them array. Every element will have the same form. I can't declare the type or make an array of tuples.
So a "tuple" in Zig is really just a struct where you don't mention any field names. For example, struct{i32,i32}
is a "tuple" with 2 integer fields.
You can define an array of those the exact same way as you can for any other struct:
// 2-element array of i32 pairs
const arr = [_]struct{i32,i32}{.{1,2}, .{3,4}};
If you just want to write a function that calls the same function with multiple different sets of args you don't even need to mention the type there, you can just leave it up to the caller to pass in the right args:
fn call_multiple(f: anytype, args_array: anytype) void {
for (args_array) |a| {
@call(.auto, f, a);
}
}
So imagine we had this:
fn sum_and_print(x: i32, y: i32) void {
std.log.debug("{} + {} = {}", .{ x, y, x + y });
}
which you can call like this:
// you can define it inline
call_multiple(&sum_and_print, &[_]struct { i32, i32 }{ .{ 1, 1 }, .{ 1, 2 }, .{ 2, 3 }, .{ 3, 5 } });
// or as a separate declaration
const args = struct { i32, i32 };
call_multiple(&sum_and_print, &[_]args{ .{ 1, 1 }, .{ 1, 2 }, .{ 2, 3 }, .{ 3, 5 } });
You can also use std.meta.ArgsTuple
to get a tuple type for the args of a function type, which you may be able to use here depending on what exactly you're trying to accomplish:
fn call_multiple_2(f: anytype, args_array: []const std.meta.ArgsTuple(@TypeOf(f))) void {
for (args_array) |a| {
@call(.auto, f, a);
}
}
call_multiple_2(sum_and_print, &.{ .{ 1, 1 }, .{ 1, 2 }, .{ 2, 3 }, .{ 3, 5 } });