4 ms·
This is really helpful in Go for `defer`. For example, if I'm manipulating files in a loop, I don't want to do: for _, fileName := range fileNames {
by throwaway894345 4y ago
This is really helpful in Go for `defer`. For example, if I'm manipulating files in a loop, I don't want to do:
for _, fileName := range fileNames {
f, err := os.Open(fileName)
if err != nil {
return err
}
defer f.Close()
doSomething(f)
}
... because I might run out of quota for open file handles. I want the defer to trigger at the end of the loop rather than at the end of the function, so I'll often put a closure in the loop body:
for _, fileName := range fileNames {
if err := func() error {
f, err := os.Open(fileName)
if err != nil {
return err
}
defer f.Close()
doSomething()
return nil
}(); err != nil {
return err
}
}
That said, I don't like the ergonomics and if I'm doing a lot of file things, I'll write a `func withFile(fileName string, callback func(*os.File) error) error` function which often composes more nicely.