Golang: Defer

By Xah Lee. Date: .

Defer statement is a new flow control, not in other popular languages.

it's used like this:

defer function_name(args)

When this is run, the args are evaluated, but the function call is not. The function is called right before the outer function exits.

package main

import "fmt"

func ff(x int) int {
    fmt.Printf("ff called. arg is %v\n", x)
    return x
}

func main() {

    var x = 3

    fmt.Printf("main. x is %v\n", x)

    defer ff(x)

    x = 4

    fmt.Printf("main. x is %v\n", x)

}

// main. x is 3
// main. x is 4
// ff called. arg is 3

Defer is used similar to “finally” in other languages, to do some clean up.

Usually, it's used right after the file opening call, to close a file.

func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()

    dst, err := os.Create(dstName)
    if err != nil {
        return
    }
    defer dst.Close()

    return io.Copy(dst, src)
}

// 2018-08-26 code from
// https://blog.golang.org/defer-panic-and-recover

Reference

The Go Programming Language Specification - The Go Programming Language#Defer_statements

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Package, Import
  3. Comment
  4. Print
  5. String
  6. Rune
  7. Variable
  8. Zero Value
  9. Constant
  10. If Then Else
  11. Switch/Case
  12. Loop
  13. Basic Types
  14. Array
  15. Slice
  16. Map
  17. Struct
  18. Function
  19. regexp
  20. Read File
  21. Write to File
  22. Walk Dir
  23. Check File Exist
  24. System Call
  25. Pointer
  26. Defer
  27. Random Number

Examples

  1. Validate Links
  2. Generate Sitemap

Reference

  1. Go Spec