In Go is it possible to iterate over a custom type?

Viewed 22862

I have a custom type which internally has a slice of data.

Is it possible, by implementing some functions or an interface that the range operator needs, to iterate (using range) over my custom type?

4 Answers

There is another option that wasn't mentioned.

You can define a Iter(fn func(int)) function which accepts some function that will be called for each item in your custom type.

type MyType struct {
    data []int
}

func (m *MyType) Iter(fn func(int)) {
    for _, item := range m.data {
        fn(item)
    }
}

And it can be used like this:

d := MyType{
    data: []int{1,2,3,4,5},
}

f := func(i int) {
    fmt.Println(i)
}
d.Iter(f)

Playground
Link to working implementation: https://play.golang.org/p/S3CTQmGXj79

Related