英文源地址
Defer用于确保函数调用在程序执行的后期执行, 通常时出于清理目的.Defer通常用于其他语言中使用的地方如ensure或者finally.
package main
import (
"fmt"
"os"
)
// 假设我们想要创建一个文件, 写入它, 然后在完成后关闭它.
// 这是我们如何用defer来做到的
func main() {
// 在使用createFile获取文件对象之后, 我们立即使用closeFile defer该文件的关闭
// 这将在writeFile完成后, 在封闭的main()函数的末尾执行.
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
// 在关闭文件时检查错误非常重要, 即使在defer函数中也是如此
func closeFile(f *os.File) {
fmt.Println("closing")
err := f.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
运行程序确认文件在写入后已关闭.
$ go run defer.go
creating
writing
closing
下一节将介绍: Recover恢复