defer用于确保稍后在程序执行中执行函数调用,通常用于清理目的。延迟(defer
)常用于例如,ensure
和finally
常见于其他编程语言中。
假设要创建一个文件,写入内容,然后在完成之后关闭。这里可以这样使用延迟(defer
)处理。
在使用createfile
获取文件对象后,立即使用closefile
推迟该文件的关闭。这将在writefile()
完成后封装函数(main
)结束时执行。
运行程序确认文件在写入后关闭。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
panic.go
的完整代码如下所示 -
package main
import "fmt"
import "os"
// 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`.
func main() {
// 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.
f := createfile("defer-test.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")
}
func closefile(f *os.file) {
fmt.println("closing")
f.close()
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run defer.go
creating
writing
closing