In my code I try to use numAddr
to record the change of num after the defer statement
func deferRun() {
num := 1
numAddr := &num
defer fmt.Printf("num is %d", *numAddr)
num = 2
return
}
func main() {
deferRun()
}
but I get num is 1
instead of 2, why does the defer function use the value instead of address of *numAddr
?
then I try another way
func deferRun() {
num := 1
numAddr := &num
defer func(intAddr *int){
fmt.Printf("num is %d", *numAddr)
}(numAddr)
num = 2
fmt.Println("num is", *numAddr)
return
}
func main() {
deferRun()
}
This time it works and I get num is 2
, so I think maybe defer fmt.Printf(something)
stored the string immediately when it was declared and the numAddr is not used when the defer function actually run?