You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
938 B
Go

package main
import (
"fmt"
"time"
)
type AsyncIterator[T any] struct {
ch chan T
}
func (it *AsyncIterator[T]) Next() (T, bool) {
v, ok := <-it.ch
return v, ok
}
func CountToFive() *AsyncIterator[int] {
it := &AsyncIterator[int]{
ch: make(chan int),
}
go func() {
defer close(it.ch)
for i := 1; i <= 5; i++ {
time.Sleep(time.Second)
it.ch <- i
}
}()
return it
}
// ModernCountToFive is an implementation of the Range-over-Func pattern of iterator.
// This was introduced in a golang 1.23+
func ModernCountToFive(yield func(int) bool) {
for i := 1; i <= 5; i++ {
time.Sleep(time.Second)
if !yield(i) {
return
}
}
}
func main() {
iter := CountToFive()
fmt.Println("Traditional (Eino style) iterator.")
for {
value, ok := iter.Next()
if !ok {
break
}
fmt.Println(value)
}
fmt.Println("Modern Range-over-Func iterator.")
for i := range ModernCountToFive {
fmt.Println(i)
}
}