How to Format Your Golang Code

Whether you like it or not, Go defines a code style at a language level (which I love), not different style guides per project. This means there’s very little opinion or conflict - and moving between projects is easy. This is very important to Go, as it stresses clarity and consistency as some of the most important factors of code style.

So you’ve written some code, but I’ve been told to format it?

Or, maybe you’ve been fixing your style manually as you go along and would like to automate it?

Go Format

or go fmt for short.

If you run this in the command line it will format the code of the project that you are located in. This comes with Go, so there’s nothing extra to install.

1
go fmt

-n (optional) will print the command (and list of files) it will run, but does nothing.

-x (optional) prints out the command it will run, then runs it.

Example In Action

golang format code