How to Format Your Golang Code

Whether you agree with it or not, Go defines a code style at a language level (which I love), and not different styles per project - or having the style as an afterthought! This means there’s very little opinion or conflict when moving between projects so it’s 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, and have been told to format it?

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

– Then go fmt in command line is your friend.

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