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 QTableWidget重绘程序崩溃
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding