來源:https://github.com/xg-wang/gobyexample/tree/master/examples
package main
import (
"fmt"
"os"
)
func main() {
//在`createFile`后得到一個文件對象,我們使用 defer 通過 `closeFile`來關(guān)閉這個文件
//這會在封閉函數(shù)(`main`)結(jié)束時執(zhí)行,就是`writeFile`結(jié)束后
f := createFile("D:/goworkspace/src/gobyexample/defer/data.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()
}
輸出結(jié)果:
creating
writing
closing
