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 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题