Defer用于確保稍后在程序執(zhí)行中執(zhí)行函數(shù)調(diào)用,通常用于清理目的。延遲(defer)常用于例如,ensure和finally常見于其他編程語言中。
假設(shè)要創(chuàng)建一個文件,寫入內(nèi)容,然后在完成之后關(guān)閉。這里可以這樣使用延遲(defer)處理。
在使用createFile獲取文件對象后,立即使用closeFile推遲該文件的關(guān)閉。這將在writeFile()完成后封裝函數(shù)(main)結(jié)束時執(zhí)行。
運行程序確認(rèn)文件在寫入后關(guān)閉。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請參考:http://www.yiibai.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()
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run defer.go
creating
writing
closing