Golang's equivalent of itertools.chain?

Issue

In Golang, how can I iterate over three slices with a single for loop, without creating a new slice containing copies of the elements in all three slices? Is there something like Python’s itertools.chain?

Solution

A simple solution using generics

package main

import "fmt"

func Chain[T any](f func(e T), slices ...[]T) {
    for _, slice := range slices {
        for _, e := range slice {
            f(e)
        }
    }
}

func main() {
    slice1 := []int{1, 2, 3}
    slice2 := []int{10, 20, 30}
    slice3 := []int{100, 200, 300}

    Chain(func(e int) {
        fmt.Println(e)
    }, slice1, slice2, slice3)
}

Output:

1
2
3
10
20
30
100
200
300

The function Chain takes a function parameter, which will be executed for each element in each slice consecutively. This function will serve as your loop body code.

The solution can be extended to retain other looping features such as break and index numbers:

func Chain[T any](f func(i int, e T) bool, slices ...[]T) {
    var i int
    for _, slice := range slices {
        for _, e := range slice {
            if !f(i, e) {
                return
            }
            i++
        }
    }
}

...

    Chain(func(i int, e int) bool {
        fmt.Println(i, "-", e)
        return (e <= 20)
    }, slice1, slice2, slice3)
...

The loop will "break" when f returns false.

Output:

0 - 1
1 - 2
2 - 3
3 - 10
4 - 20
5 - 30

Answered By – Hymns For Disco

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.