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?
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.