defer 关键字(参看 6.4)对于在函数结束时关闭打开的文件非常有用,例如下面的代码片段:
defer
func data(name string) string { f, _ := os.OpenFile(name, os.O_RDONLY, 0) defer f.Close() // idiomatic Go code! contents, _ := ioutil.ReadAll(f) return string(contents) }
在函数 return 后执行了 f.Close()
f.Close()
To view this video please enable JavaScript,and consider upgrading to a web browser that supports HTML5 video
This is a modal window.
Beginning of dialog window.Escape will cancel and close the window.
End of dialog window.