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,再执行删除操作了。

相关文章:

  • 2022-12-23
  • 2022-02-16
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2023-01-10
  • 2022-12-23
  • 2021-05-21
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
  • 2022-02-05
  • 2021-08-11
  • 2022-01-18
  • 2022-01-15
相关资源
相似解决方案