golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.55k stars 519 forks source link

tour: flowcontrol/12 - better example? #634

Open pratham2003 opened 5 years ago

pratham2003 commented 5 years ago

Context: https://tour.golang.org/flowcontrol/12

I'm new to Go. Can someone suggest a better (easier to understand) example to explain the following statement? The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

I tried something to explain the above but I feel it's too complicated to be introduced so early in the tour.

package main

import (
    "fmt"
    "strconv"
)

func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

func main() {
    nextInt := intSeq()

    defer fmt.Println("world - " + strconv.Itoa(nextInt()))

    fmt.Println("hello - " + strconv.Itoa(nextInt()))
}
arjunbazinga commented 5 years ago

Take the example

package main
import "fmt"

func main() {
    i :=1
    defer fmt.Println(i+1)
    i = 5
    fmt.Println(i)
}

Output

5
2

The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function.

If the arguments were not evaluated immediately then output would be

5
6