SoFunction
Updated on 2025-03-04

Summary of the use of the defer function of Golang learning notes

Golang's defer is elegant and simple, which is one of the highlights of Golang. Defer will not be executed immediately when declared, but after the function returns, each defer is executed in sequence according to the principle of first-in and then exiting. It is generally used to release resources, clean up data, record logs, and handle exceptions.

The keyword defer is called late in registration. These calls are not executed until ret and are usually used to free resources or to handle errors.

1. When defer is declared, its parameters will be parsed in real time.

func a() {
  i := 0
  defer (i) //Output 0, because i is 0 at this time  i++
  defer (i) //Output 1, because i is 1 at this time  return
}

2. When defer is called multiple times in a function, Go will put the defer call into a stack and then execute it in the order of first in and then exit.

func main() {
  defer ("1")
  defer ("2")
  defer ("3")
  defer ("4")
}

The output order is 4321

Use defer to output string inverse order

name := "Hello Naveen"
  ("%s\n", string(name))
  ("Reverse order:")
  defer ("\n")
  for _, v := range []rune(name) {
    defer ("%c", v)
  }

Output:

Hello Naveen

Reverse order: OK you neevaN

III. The practical application of defer

func (r rect) area(wg *) {
  if  < 0 {
    ("rect %v's length should be greater than zero\n", r)
    ()
    return
  }
  if  < 0 {
    ("rect %v's width should be greater than zero\n", r)
    ()
    return
  }
  area :=  * 
  ("rect %v's area %d\n", r, area)
  ()
}

We will find that the above() is called many times and we can use defer to optimize the code

func (r rect) area(wg *) {
  defer ()
  if  < 0 {
    ("rect %v's length should be greater than zero\n", r)
    return
  }
  if  < 0 {
    ("rect %v's width should be greater than zero\n", r)
    return
  }
  area :=  * 
  ("rect %v's area %d\n", r, area)
}

Defer delay call will be called before the end of the program

Here is an example:

package main 
import "fmt" 
func deferTest(number int) int {
 defer func() {
 number++
 ("three:", number)
 }()
 
 defer func() {
 number++
 ("two:", number)
 }()
 
 defer func() {
 number++
 ("one:", number)
 }()
 
 return number
}
 
func main() {
 ("Function return value:", deferTest(0))
}

The above code prints the result:

one: 1
two: 2
three: 3
Function return value: 0

PS: defer has an important feature. Even if the function throws an exception, defer will be executed. In this way, the resource will not be released due to errors in the program.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.