-
-
Save benbjohnson/9eebd201ec096ab6430e1f33411e6427 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 ownif
block.@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 deferredClose()
since it would either be caused by another error happening (e.g.Write()
) or it'd be the second call toClose()
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.