Thanks for your wonderful explanation.

On Tue, Sep 3, 2024 at 5:53 AM Ian Lance Taylor <i...@golang.org> wrote:

> On Mon, Sep 2, 2024 at 4:36 PM vignes waran
> <vigneswarank.kar...@gmail.com> wrote:
> >
> > 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!"
>
> 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
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAKaFSX43gXp_gy0sPGbmr5Dmg0b%3DOU7F54J-u8O4SPXwouRncA%40mail.gmail.com.

Reply via email to