Hacker News new | past | comments | ask | show | jobs | submit login

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).



What can you do if you detect an error in a "defer" clause? Besides panic?


With 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.


Well, 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.


One thing you can do is simply use BOTH a defer Close and a straight-path Close with error-checking.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: