Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go延迟(defer)实例
Go延迟(defer)实例
作者:--    发布时间:2019-11-20

defer用于确保稍后在程序执行中执行函数调用,通常用于清理目的。延迟(defer)常用于例如,ensurefinally常见于其他编程语言中。

假设要创建一个文件,写入内容,然后在完成之后关闭。这里可以这样使用延迟(defer)处理。

在使用createfile获取文件对象后,立即使用closefile推迟该文件的关闭。这将在writefile()完成后封装函数(main)结束时执行。

运行程序确认文件在写入后关闭。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html

panic.go的完整代码如下所示 -

package main

import "fmt"
import "os"

// 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`.
func main() {

    // 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.
    f := createfile("defer-test.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()
}

执行上面代码,将得到以下输出结果 -

f:\worksp\golang>go run defer.go
creating
writing
closing

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册