码迷,mamicode.com
首页 > 其他好文 > 详细

【Golang基础】defer执行顺序

时间:2019-12-22 12:50:28      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:bec   some   ESS   another   open   不能   access   sed   can   

defer 执行顺序类似栈的先入后出原则(FILO)
 
 
一个defer引发的小坑:打开文件,读取内容,删除文件
 
 
// 原始问题代码
func testFun(){
        // 打开文件
    file, err := os.Open(path)
    defer file.Close()
    // do something
 
    // 删除文件
    defer func() {
       removeErr := os.Remove(path)
       if removeErr != nil {
          fmt.Println(removeErr)
       }
    }()
}

 

  

 
如果像上面这样写的话,实际开发时是会报错的。
 
The process cannot access the file because it is being used by another process.
错误原因也很明了:这个文件被其他程序占用了,不能够删除。主要是因为file处于未关闭状态,所以不能进行删除操作
 
// 修正后的代码
func testFun(){
    // 打开文件
    file, err := os.Open(path)
    // do something
 
 
    // 删除文件
    defer func() {
       removeErr := os.Remove(path)
       if removeErr != nil {
          fmt.Println(removeErr)
       }
    }()
    defer file.Close()
}
我们需要调整defer的顺序,这样的话会就会先关闭file,再执行删除操作了。

【Golang基础】defer执行顺序

标签:bec   some   ESS   another   open   不能   access   sed   can   

原文地址:https://www.cnblogs.com/hwtblog/p/12079284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!