Defer {.en}

推迟 {.zh}

::: {.en} Defer is used to ensure that a function call is performed later in a program’s execution, usually for purposes of cleanup. defer is often used where e.g. ensure and finally would be used in other languages. :::

::: {.zh}

Defer用于确保稍后在程序执行中执行函数调用,通常用于清理。经常使用defer,例如.ensurefinally将用于其他语言。

:::

  1. package main
  2. import "fmt"
  3. import "os"

::: {.en} Suppose we wanted to create a file, write to it, and then close when we’re done. Here’s how we could do that with defer. :::

::: {.zh}

假设我们想要创建一个文件,写入它,然后在我们完成时关闭。这就是我们用defer来做到这一点的方法。

:::

  1. func main() {

::: {.en} Immediately after getting a file object with createFile, we defer the closing of that file with closeFile. This will be executed at the end of the enclosing function (main), after writeFile has finished. :::

::: {.zh}

在使用createFile获取文件对象后,我们立即将该文件的关闭推迟到closeFile。在writeFile完成之后,这将在封闭函数(main)的末尾执行。

:::

  1. f := createFile("/tmp/defer.txt")
  2. defer closeFile(f)
  3. writeFile(f)
  4. }
  5. func createFile(p string) *os.File {
  6. fmt.Println("creating")
  7. f, err := os.Create(p)
  8. if err != nil {
  9. panic(err)
  10. }
  11. return f
  12. }
  13. func writeFile(f *os.File) {
  14. fmt.Println("writing")
  15. fmt.Fprintln(f, "data")
  16. }
  17. func closeFile(f *os.File) {
  18. fmt.Println("closing")
  19. f.Close()
  20. }

::: {.en} Running the program confirms that the file is closed after being written. :::

::: {.zh}

运行程序确认文件在写入后关闭。

:::

  1. $ go run defer.go
  2. creating
  3. writing
  4. closing