Skip to content

Instantly share code, notes, and snippets.

@NaniteFactory
Created December 6, 2019 08:24
Show Gist options
  • Save NaniteFactory/fdc008044b64c56875a03219c7f3ab90 to your computer and use it in GitHub Desktop.
Save NaniteFactory/fdc008044b64c56875a03219c7f3ab90 to your computer and use it in GitHub Desktop.
Nested function calls in a defer statement.
package main
import "log"
func foo1(n int) int {
log.Println("foo1", n)
return n
}
func foo2(n int) int {
log.Println("foo2", n)
return n
}
func foo3(n int) int {
log.Println("foo3", n)
return n
}
func deferOneFunctionCall() {
defer foo1(foo2(foo3(1)))
log.Println("defer-----")
}
func deferThreeFunctionCalls() {
defer func() { foo1(foo2(foo3(1))) }()
log.Println("defer-----")
}
// Nested function calls in a defer statement.
//
// A defer statement defers only a single function.
// This means any function call evaluating an argument to a deferred function is not deferred.
// Each time a defer statement executes, the function value and parameters to the call are evaluated as usual.
func main() {
log.Println("deferOneFunctionCall()")
deferOneFunctionCall()
log.Println()
log.Println("deferThreeFunctionCalls()")
deferThreeFunctionCalls()
}
// 2019/12/06 17:23:56 deferOneFunctionCall()
// 2019/12/06 17:23:56 foo3 1
// 2019/12/06 17:23:56 foo2 1
// 2019/12/06 17:23:56 defer-----
// 2019/12/06 17:23:56 foo1 1
// 2019/12/06 17:23:56
// 2019/12/06 17:23:56 deferThreeFunctionCalls()
// 2019/12/06 17:23:56 defer-----
// 2019/12/06 17:23:56 foo3 1
// 2019/12/06 17:23:56 foo2 1
// 2019/12/06 17:23:56 foo1 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment