ZhangZhihui's Blog  

We will implement a function that opens a set of files where the file paths are received via a channel. Hence, we have to iterate over this channel, open the files, and handle the closure. Here’s our first version:

There is a significant problem with this implementation. We have to recall that defer schedules a function call when the surrounding function returns. In this case, the defer calls are executed not during each loop iteration but when the readFiles function returns. If readFiles doesn’t return, the file descriptors will be kept open forever, causing leaks.

 

What are the options to fix this problem? One might be to get rid of defer and handle the file closure manually. But if we did that, we would have to abandon a convenient feature of the Go toolset just because we were in a loop. So, what are the options if we want to keep using defer? We have to create another surrounding function around defer that is called during each iteration.
For example, we can implement a readFile function holding the logic for each new file path received:

 

Another approach could be to make the readFile function a closure:

 

posted on 2024-02-21 09:23  ZhangZhihuiAAA  阅读(5)  评论(0编辑  收藏  举报