-
-
Save benbjohnson/9eebd201ec096ab6430e1f33411e6427 to your computer and use it in GitHub Desktop.
func doSomething() error { | |
f, err := os.Create("foo") | |
if err != nil { | |
return err | |
} | |
defer f.Close() | |
if _, err := f.Write([]byte("bar"); err != nil { | |
return err | |
} | |
if err := f.Close(); err != nil { | |
return err | |
} | |
return nil | |
} |
Hi. Thank you very much for sharing your knowledge.
f.Close
will return an error if it has already been called. Do you want to explicitly ignore the error in the defer operation due to the second call? If so, is there any collateral damage we should worried about due to this error?
Thanks again!
Why not just return f.Close() instead of if statement?
@abonec Sorry for the really long delay. Not sure how I missed your question. Yes, returning f.Close()
is fine too. These days I'd also typically return a wrapped error message with %w
so that would require its own if
block.
Do you want to explicitly ignore the error in the defer operation due to the second call? If so, is there any collateral damage we should worried about due to this error?
@zucchinidev The deferred Close()
is there just to ensure that it's definitely closed by the end. There's nothing I can really do to handle an error from the deferred Close()
since it would either be caused by another error happening (e.g. Write()
) or it'd be the second call to Close()
so it'd be a no-op. I've used this pattern a lot over the years and it works great. I haven't had any issues with it.
Why not just return f.Close() instead of if statement?