Usage analysis of GO language delay function defer

  • 2020-05-09 18:43:27
  • OfStack

This article illustrates the use of the GO language delay function defer. Share with you for your reference. The specific analysis is as follows:

defer does not execute immediately when it is declared, but each defer is executed in sequence after the function return and then FILO (first in, last out), which is generally used for exception handling, resource release, data cleaning, logging, and so on. This is a bit like an object-oriented language destructor, elegant and simple, and is one of the highlights of Golang.

Code 1: understand the order in which defer is executed

package main
import "fmt"
func fn(n int) int {
 defer func() {
  n++
  fmt.Println("3st:", n)
 }()  defer func() {
  n++
  fmt.Println("2st:", n)
 }()  defer func() {
  n++
  fmt.Println("1st:", n)
 }()  return n // I didn't do anything
} func main() {
 fmt.Println(" Function return value: ", fn(0))
}

Output:

1st: 1
2st: 2
3st: 3
The return value of the function: 0

Code 2: classic application example

func CopyFile(dst, src string) (w int64, err error) {
 srcFile, err := os.Open(src)
 if err != nil {
  return
 }
 defer srcFile.Close() // Every time you apply for a resource, get used to applying right away 1 a defer Close the resource so you don't forget to release it  dstFile, err := os.Create(dst)
 if err != nil {
  return
 }
 defer dstFile.Close()  return io.Copy(dstFile, srcFile)
}

Another important feature of defer is that it is executed even if the function throws an exception. This prevents the resource from being released because of a program error.

I hope this article has helped you with the GO programming language.


Related articles: