dongyou8701 2017-10-02 08:01
浏览 9
已采纳

如何理解延期陈述

I have two examples about defer statement in golang, the first one is incorrect, and the second one is correct. But I think they have the same problem, in my opinion I think the second still has risk that run out of file descriptors, could any one can help me to clarify why the second is correct? Thanks!

Example1:

for _, filename := range filenames {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close() // NOTE: risky; could run out of file descriptors
    // ...process f...
 }

Example2:

for _, filename := range filenames {
    if err := doFile(filename); err != nil {
        return err
    }
}
func doFile(filename string) error {
    f, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer f.Close()
    // ...process f...
}
  • 写回答

1条回答 默认 最新

  • duanchu3376 2017-10-02 08:07
    关注

    Deferred functions run when the enclosing function returns. Spec: Defer statements:

    A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

    In your first example you use a single for loop in which you use defer statements, but the deferred functions will not get executed at the end of the iterations, only after the for loop (when the enclosing function ends). This means all the files you open inside the for loop will remain open 'till the "end". If filenames contains a thousand valid file names, the loop will (try to) open a thousand files before starting to close any of them.

    In your second example you "outsourced" dealing with the files to a separate function. Using defer in this function is fundamentally different, as when this function returns, the deferred function (File.Close()) will be called first. So in your second example at most 1 file is open at all times by the posted code, no matter how many elements filenames contains.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)