Home > Back-end >  Defer and println reference issues?
Defer and println reference issues?

Time:02-27

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

CodePudding user response:

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

CodePudding user response:

I think you could try looking at the source code agint.

  •  Tags:  
  • go
  • Related