3 ms·
This is a gripe I have about Go -- a very minor gripe, to be sure, but it's still there. If you want to iterate over two arrays/slices that have the same length
by nemo1618 4y ago
This is a gripe I have about Go -- a very minor gripe, to be sure, but it's still there. If you want to iterate over two arrays/slices that have the same length, you have to choose between:
for i := 0; i < n; i++ {
fn(foo[i], bar[i])
}
for i := range foo {
fn(foo[i], bar[i])
}
for i := range bar {
fn(foo[i], bar[i])
}
for i, x := range foo {
fn(x, bar[i])
}
for i, y := range bar {
fn(foo[i], y)
}
But none of these are satisfactory; what I really want to write is:
for _, (x, y) := range (foo, bar) {
fn(x, y)
}
- maxmcd 4y agoThis is pretty ugly and add the overhead of a function callback, but just for fun: func multiLoop[X, Y any](x []X, y []Y, cb func(i int, x X, y Y)) { if len(x) != len(y) { panic("invalid slice lengths") } for i := 0; i < len(x); i++ { cb(i, x[i], y[i]) } } func foo() { multiLoop([]int{1, 2, 3}, []string{"a", "b", "c"}, func(i int, x int, y string) { fmt.Println(i, x, y) }) }
- masklinn 4y agoFWIW this is often called `zipWith`, or sometimes just `map` (some `map` implementations can take a variable number of sequences to map over).