gobyexample-defer

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

package main

import (
    "fmt"
    "os"
)

func main() {
    //在`createFile`后得到一个文件对象,我们使用 defer 通过 `closeFile`来关闭这个文件
    //这会在封闭函数(`main`)结束时执行,就是`writeFile`结束后
    f := createFile("D:/goworkspace/src/gobyexample/defer/data.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()
}

输出结果:

creating
writing
closing

![image.png](https://upload-images.jianshu.io/upload_images/7547037-88ba7b6245df45af.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容