当前位置: 代码迷 >> 综合 >> 用 defer 关闭文件
  详细解决方案

用 defer 关闭文件

热度:132   发布时间:2023-10-20 06:33:29.0

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

转载地址

https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/12.7.md