Thursday, July 02, 2015

Dirty Go: eliminating vertical space

Having written a lot of Go I sometimes find myself exasperated by functions like this:

because of all the repetition and vertical space. Working on something the other day I realized I could (ab-)use Go's switch like this:

with a small change to the functions being called. Instead of having doFirst (etc.) return an error, have it take a pointer to an error and return a boolean indicating success. That's so much more compact, but feels a little dirty.

PS You can play about with that here.


Unknown said...

But of course you'd never use bare returns unless they make the function signature more clear, or as required for doing defer magic.... right? :)

Unknown said...

Can't you just chain your new bool-returning functions with logical or?

An 'on err: return 0, err' would bring the normal three lines down to a compact one. The expression would have to be bool or the built-in error type to avoid the noisy 'err != nil'.