Defer用於確保在程式執行過程中稍後執行函式呼叫,通常用於清理功能。defer 通常使用於在其他語言中使用ensure 和finally 的地方。
|
|
|

package main
|
|
import (
"fmt"
"os"
)
|
假如我們想要建立一個檔案,寫入它,然後在完成時關閉。以下是我們如何使用defer 做到這件事。
|
func main() {
|
使用createFile 取得檔案物件後,隨即遞延使用closeFile 關閉該檔案。這將在封裝函式 (main ) 結束時執行,也就是writeFile 完成後。
|
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")
|
|
}
|
即使在遞延函式中,檢查關閉檔案時發生的錯誤也很重要。
|
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)
}
}
|