3 ms·
The end of the article has my favorite solution. This is also how I'd solve it in Rust, except the defer would be implicit. func doSomething() error {
by iudqnolq 2y ago
The end of the article has my favorite solution.
This is also how I'd solve it in Rust, except the defer would be implicit.
func doSomething() error {
f, err := os.Create("foo")
if err != nil { return err }
defer func(){ _ = f.Close() }()
if _, err := f.Write([]byte("bar"); err != nil { return err }
return f.Close()
}
- klodolph 2y agoYes, note you’ll also see: defer f.Close() Instead of, defer func(){ _ = f.Close() }() I think this is likely a code style difference due to working with a linter that alarms on discarded error returns, but I’m not sure. Both options have the same behavior, unless you reassign f (defer f.Close() will use the original value, defer func() ... will use the current value).
- iudqnolq 2y agoYup, I wrote it that way because I have a linter for unused error returns with a handful of exceptions (like closing http request bodies).
- klodolph 2y agoI think I would add an exception for this too, because it crops up a lot.
- iudqnolq 2y agoI can't decide because in this pattern you ignore once and check once and I like the lint for the check. Ideally the linter could recognize this pattern. Even better would be if the linter could catch when you never close, I've made that mistake a few times.