0

I just wrote the below code and could not understand why n2 is printed as 2. And my understanding is n2 should be printed as 0.

package main

import "fmt"

func curryAddTwo(n1 int) (n2 int) {
    defer func() {
        fmt.Println(n2) // why it prints 2?
    } ()

    return 2
}

func main()  {
      fmt.Println(curryAddTwo(1))
}

zhuangyan@C02D91SMMD6R ~/coding/go/closure $ ./main
2
2
azhuang
  • 39
  • 6
  • 3
    See https://golang.org/ref/spec#Return_statements and https://golang.org/ref/spec#Defer_statements -- note that `return 2` is equivalent to `n2 = 2; return` in the last line of `curryAddTwo`. So `n2` has been set to `2` at the time the anonymous closure is called. – torek Aug 01 '21 at 04:22
  • @torek Thanks a lot! And my question was solved. – azhuang Aug 01 '21 at 07:44

0 Answers0