3 ms·
Couldn't you do: func closeIfNecessary(object interface{}) { closable, needsClosing := object.(closable) if needsClosing { clos
by pcwalton 9y ago
Couldn't you do:
func closeIfNecessary(object interface{}) {
closable, needsClosing := object.(closable)
if needsClosing {
closable.close()
}
}
And then just do:
func f(i interface{}) {
defer closeIfNecessary(i)
...
}
Doing it this way also saves you boilerplate by factoring the downcast out into a separate function.
- Groxx 9y agoAs long as you can always call .close() regardless of the code below, yep - that'd work, and is definitely more readable. If you can't call it unless [some other conditions], it goes back to the same kind of problem though. "closable" may not be a good choice on my part, as they're often called unconditionally.