gofmt, goimports, goreturns — why do we need three formatters?!

I started working on a new golang project today and I spent bigger portion of my morning just trying to understand the formatter situation in the golang space. The project in question was running build time checks using `gofmt` and `goimports` to see if the code entering the repo is properly formatted. So that’s two different formatters already. And then I went into settings of my VSCode to find out it’s using `goreturns` to format code. And then I was like (╯°□°)╯︵ ┻━┻ and I had to understand what all those tools actually bring and which one to choose.

After a bit of reading and actually realizing others are confused as well I found all that really simple and kind of funny.

To start with, there is `gofmt` which is what you get as part of `go` tool pre-packaged. With every go compiler you can just run `go fmt` and don’t need to install anything else. And BAM — your code is formatted.

You might want something more, there’s `goimports` it lives pretty close to golang itself in the go tools repo. To use it, you need to install it though using `go get -u golang.org/x/tools/cmd/goimports`. What’s interesting is that `goimports` is using `gofmt` underneath. So it is superset of `gofmt`, on top of formatting it fixes your imports.

And `goreturns` is going even one level further. It has a flag that allows you to run what `goimports` does and then on top of that it runs it’s extra rules. It does not have any value to run it as part of CI, when plugged in to your IDE it brings some extra sugar on top when composing return statements.

To sum it up, use `goimports` in CI and `goreturns` in your IDE and you’re fine.

Also I think this simplifies things quite a bit:

gofmt = golang formatter

goimports = gofmt + fixing imports

goreturns = goimports + return statement syntactic sugar

Passionate about traveling, food and programming. Tennis player that works on container orchestration at Mesosphere. Always trying to improve.

Passionate about traveling, food and programming. Tennis player that works on container orchestration at Mesosphere. Always trying to improve.