Rangefunc in Go 1.23

148 views
Skip to first unread message

Justin Scheiber

unread,
Jul 10, 2024, 7:17:30 PM (6 days ago) Jul 10
to golang-nuts
Howdy,

I'm trying to establish a mental model for what the compiler does with range functions in Go 1.23.  It looks like the compiler creates a function based on the for loop body, and calls it by looping over the values passed in.

Meaning this code:
func simpleIter(yield func(v int) bool) {
    if !yield(1) { 
        return 
    }
    if !yield(2) { 
        return 
    }
}

for x := range simpleIter {
    fmt.Println(x)
}

compiles into this code:

{
yield := func(v int) bool {
fmt.Println(v) // loop body from the code above
}
for v := 1; v <= 2; v++ {
if !yield(1) {
goto end_loop
}
}
end_loop:
}

Is that correct?

Thanks,

Justin

Ian Lance Taylor

unread,
Jul 11, 2024, 12:04:18 AM (6 days ago) Jul 11
to Justin Scheiber, golang-nuts
Sort of. I 'm not sure where the "for v := 1; v <= 2; v++" comes
from. Your yield function is more or less correct, but then the
compiler just calls "simpleIter(yield)".

It's a bit more complicated because the loop can contain break
statements, return statements, or panics. Those cause the generated
yield function to return false.

Ian
Reply all
Reply to author
Forward
0 new messages