来源:https://github.com/xg-wang/gobyexample/tree/master/examples
package main
import (
"fmt"
"os"
)
func main() {
//在`createFile`后得到一个文件对象,我们使用 defer 通过 `closeFile`来关闭这个文件
//这会在封闭函数(`main`)结束时执行,就是`writeFile`结束后
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()
}
输出结果:
creating
writing
closing
![image.png](https://upload-images.jianshu.io/upload_images/7547037-88ba7b6245df45af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)