On Wed, Jul 10, 2024 at 4:17 PM Justin Scheiber <jschei...@gmail.com> wrote:
>
> 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?

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

-- 
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/CAOyqgcVmV8%3D9f6SbL-2u192NLONi35mbBE-gaEgGzSB15EYtmQ%40mail.gmail.com.

Reply via email to