12.7. 用 defer 关闭文件

未匹配的标注

defer 关键字(参看 6.4)对于在函数结束时关闭打开的文件非常有用,例如下面的代码片段:

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()

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
贡献者:1
讨论数量: 0
发起讨论 查看所有版本


暂无话题~