Defer {.en}
推迟 {.zh}
::: {.en}
Defer is used to ensure that a function call is
performed later in a program’s execution, usually for
purposes of cleanup. defer
is often used where e.g.
ensure
and finally
would be used in other languages.
:::
::: {.zh}
Defer用于确保稍后在程序执行中执行函数调用,通常用于清理。经常使用defer
,例如.ensure
和finally
将用于其他语言。
:::
package main
import "fmt"
import "os"
::: {.en}
Suppose we wanted to create a file, write to it,
and then close when we’re done. Here’s how we could
do that with defer
.
:::
::: {.zh}
假设我们想要创建一个文件,写入它,然后在我们完成时关闭。这就是我们用defer
来做到这一点的方法。
:::
func main() {
::: {.en}
Immediately after getting a file object with
createFile
, we defer the closing of that file
with closeFile
. This will be executed at the end
of the enclosing function (main
), after
writeFile
has finished.
:::
::: {.zh}
在使用createFile
获取文件对象后,我们立即将该文件的关闭推迟到closeFile
。在writeFile
完成之后,这将在封闭函数(main
)的末尾执行。
:::
f := createFile("/tmp/defer.txt")
defer closeFile(f)
writeFile(f)
}
func createFile(p string) *os.File {
fmt.Println("creating")
f, err := os.Create(p)
if err != nil {
panic(err)
}
return f
}
func writeFile(f *os.File) {
fmt.Println("writing")
fmt.Fprintln(f, "data")
}
func closeFile(f *os.File) {
fmt.Println("closing")
f.Close()
}
::: {.en} Running the program confirms that the file is closed after being written. :::
::: {.zh}
运行程序确认文件在写入后关闭。
:::
$ go run defer.go
creating
writing
closing