Defer and println reference issues?

Viewed 54

I want to know why is there is 0 and not 1?

That is a pointer not a value.thanks guys.

package main

import "fmt"

func main() {
    var i = new(int)
    defer func(i *int) {
        fmt.Printf("3:%p,%v\n", i, *i)
    }(i)
    defer fmt.Printf("2:%p,%v\n", i, *i)
    *i++
    fmt.Printf("1:%p,%v\n", i, *i)
}

//1:0x1400001c0a0,1
//2:0x1400001c0a0,0
//3:0x1400001c0a0,1
2 Answers

I hope this simple and clear example will help to understand what is written in the documentation.

import "fmt"

func params() int {
    fmt.Println("params")
    return 0
}

func f(int) {
    fmt.Println("deferred")
}

func main() {
    defer f(params())
    fmt.Println("exit")
}

and the result

params
exit
deferred

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

In the first defer, you use the parameter i which is received when calling the func. In the second defer fmt.Printf("2:%p,%v\n", i, *i), the value of I is already evaluated, before *i++

Related