Is there syntax for destructuring a tuple in a for loop?

I have a few arrays of tuples and I’m currently using this syntax to loop through them:

for (my_array) |tup| {
    const a, const b, const c = tup;
    // Do something with a, b, c.
}

Does zig have any way to integrate the tuple destructuring up into the for syntax? For example, something along the lines of:

for (my_array) |(a, b, c)| {
    // Do something with a, b, c.
}

I can’t find any mention in documentation, so I assume not, but I figure it’s best to check with the community.

Nope. And my understanding (based on other conversations) is that it will not be added.

2 Likes

I think that’s for the best even though it would be nice:

for (a, b) |c, d, e| {
   // One of a or b is a tuple. But which?
}

Zig goes to an unusual amount of effort to prevent semantics from bleeding into syntax like this, and it’s good that it does.

4 Likes

In functional languages it would likely be something like:

for (a, b) |c, (d, e)| {
   // ...
}

But I am glad you can’t write:

for (a, b) |c, ((d, (e, (f, g))), h, i)| {
   // ...
}

I think we are better off without it.

4 Likes

syntax of tuple desturcturing in for loops aside, what I’d really love to have is being able to switch on multiple things at once. some thing like this

const E = enum {
	a,
	b,
	c,
};

const F = enum {
	d,
	e,
	f,
};


const e: E = .a;
const f: F = .d;

switch (e,f) {
	.a, .d => // etc
}

I am aware of the many rought edges of this specially the inline else having two payloads and whatnot .. but it would be nice ..

1 Like