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.

2 comments:

Nate Finch 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? :)

Ralph Corderoy said...

Can't you just chain your new bool-returning functions with logical or? https://play.golang.org/p/iFsNFxD_ja

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