Difference between defer call a function directly and call it in an anonymous function?

Viewed 523

I got some code like this.

import (
  "fmt"
)

func ShowResult(result []string) {
  fmt.Println(result)
}

func main() {
  result := []string{}
  defer func() {
    ShowResult(result)
  }()
  defer ShowResult(result)
  result = append(result, "test")
}

And the result is:

[]
[test]

So could anyone tell me what is difference between calling a function directly and calling it in an anonymous function when defer?

1 Answers

The function arguments are evaluated when it is deferred. From the documentation

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked

When your deferred function is a closure, the ShowResult arguments are not evaluated until the closure is executed, which is immediately after the outer function returns and after the result value has been modified.

Related