Iterators

260 views
Skip to first unread message

vignes waran

unread,
Sep 2, 2024, 7:36:09 PMSep 2
to golan...@googlegroups.com
I have been trying to understand the concept of iterators introduced in the new Go 1.23 release, but I’m struggling to comprehend how the iteration call happens multiple times and where the boolean value for stopping the loop is obtained. Here’s my code snippet for reference:

package main

import "fmt"

func Countdown(v int) func(func(int) bool) {
fmt.Println("v :", v) // This function runs only one time
return func(f func(int) bool) {
for i := v; i >= 0; i-- {
if !f(i) {
return
}
}
}
}

func main() {
// fmt.Println("Countdown :", Countdown(2))
for x := range Countdown(2) {
fmt.Println(x)
}
}

I appreciate any help in understanding this concept better. Thanks in advance!"

Ian Lance Taylor

unread,
Sep 2, 2024, 8:24:14 PMSep 2
to vignes waran, golan...@googlegroups.com
The compiler wraps the loop body into a function closure, more or less like:

func $loop(x int) bool {
fmt.Println(x)
return true
}

It then changes the for statement into Countdown(2)($loop).

For many more details, which are approximately but not precisely what
the Go 1.23 compiler does, see https://research.swtch.com/coro.

Ian

vignes waran

unread,
Sep 7, 2024, 11:26:08 AMSep 7
to Ian Lance Taylor, golan...@googlegroups.com
Thanks for your wonderful explanation. 
Reply all
Reply to author
Forward
0 new messages