3 ms·
To be fair I think most Go programmers are exposed to defer .Close() on files via example, and it's possible every copied example can be traced back to some pro
by smarterclayton 10y ago
To be fair I think most Go programmers are exposed to defer .Close() on files via example, and it's possible every copied example can be traced back to some proto-example in the very early days of Go. It is extremely pernicious in the ecosystem - Docker, Kubernetes, and etcd all had rounds of cleaning it up over the last year or two. I would expect linters to flag Close without checking the error value (if they don't already).
- Animats 10y agoWhat can you do if you detect an error in a "defer" clause? Besides panic?
- ansible 10y agoWell, I don't know if panic is the right option. However, checking the return value is always a good idea, and any errors should at least be logged. I too wish it was less cumbersome to use defer properly.
- giovannibajo1 10y agoOne thing you can do is simply use BOTH a defer Close and a straight-path Close with error-checking.
- amscanne 10y agoWith named return values, the defer can modify them. For example: func Foo() (err error) { defer func() { err = errors.New("some error") }() } The function will return the "some error" error.