I have a tuple with similarly-typed elements. (Every element in all_leds is a struct Pin(X), where X is a comptime value.) And I’d like to call a specific function (pin.toggle()) on element j. How do I do that, idiomatically?
The cleanest way I found is the following. But I’m probably missing a simpler alternative?
/// For the given `tuple` element `j`, call the given function `f` with return type `R`.
fn forTupleElementDo(tuple: anytype, j: usize, comptime R: type, f: fn (anytype) R) R {
inline for (0..tuple.len) |i| {
if (i == j) {
f(@field(tuple, std.fmt.comptimePrint("{d}", .{i})));
}
}
}
@Sze Thanks for showing me that the tuple[i] syntax does work for a comptime-known i! Obvious in retrospect, and the compiler must have suggested this to me, and actually used in a code example in the manual at https://ziglang.org/documentation/0.13.0/#Tuples, but I’d missed it.
And switch-with-inline else works perfectly fine as well for a runtime-known j, especially in my special case where the tuple length is a power of 2 (namely 8, so that the index range is the range of an u3):