SoFunction
Updated on 2025-03-01

Talk about the use of golang's defer

sequence

This article mainly studies golang's defer

defer

  • Return first assign a value (for named return value), then execute defer, and finally the function returns
  • The execution order of defer function calls is the opposite of the execution order of the defer statements to which they belong respectively
  • The expression after defer can be a call to func or method. If the defer function is nil, panic will be

Example

Example 1

// f returns 42
func f() (result int) {
  defer func() {
    // result is accessed after it was set to 6 by the return statement
    result *= 7
  }()
  return 6
}

Here, return first assigns the result to 6, then executes defer, result becomes 42, and finally returns 42

Example 2

func f() int {
  result := 6
  defer func() {
    // result is accessed after it was set to 6 by the return statement
    result *= 7
  }()
  return result
}

Here, return determines the return value 6, then defer modifies the result, and finally the function returns the return value determined by return.

Example 3

func multiDefer() {
  for i := 3; i > 0; i-- {
    defer func(n int) {
      (n, " ")
    }(i)
  }

  for i := 3; i > 0; i-- {
    defer (i, " ")
  }
}

Multiple defer functions are executed in reverse order in order, here output 1 2 3

Example 4

var fc func() string

func main() {
  ("hello")
  defer fc()
}

Since the func specified by defer is nil, here panic

Example 5

func main() {
  for i := 3; i > 0; i-- {
    defer func() {
      (i, " ")
    }()
  }
}

Since the func called defer has no parameters, when executed, i is already 0, so 3 0s are output here

summary

Defer can be disassembled into return assignment, defer is executed, and the last code returns three steps; the order of defer is executed in reverse order.

doc

Defer_statements
Golang's Defer
Defer execution timing and FAQ in golang

This is the end of this article about the use of golang defer. For more related golang defer content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!