延迟执行关闭文件的操作

huangapple go评论88阅读模式
英文:

Delay execution of closing a file

问题

在Go语言中,你可以在打开文件时声明文件句柄在首次打开时关闭,并在(函数?方法?垃圾回收?)结束时自动关闭。

这个语法是怎样的,它被称为什么?

英文:

I remember reading about a feature of go in that you can declare a file handle to be closed when you first open it, and at the end of the (function? method? garbage collection?) it would automatically close.

What is the syntax for this and what is it called?

答案1

得分: 5

看起来你需要使用defer关键字。这个关键字可以让你指定在函数退出时执行的语句。例如:

defer f.Close()

延迟清理程序的执行顺序与它们创建的顺序相反。

英文:

It sounds like you are after the defer keyword. This lets you specify statements that will be executed when the function exits. For example:

defer f.Close()

Deferred cleanup routines are executed in the opposite order they are created.

huangapple
  • 本文由 发表于 2013年9月17日 16:38:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/18845084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定