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...
}