英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论