Go fmt, the Go Style Guide
A programming style guide is a description (formal or informal) of how a programmer should write code in a given language. So is there a Go style guide? Well, not exactly, but sort of. Instead of a style guide Go provides the Go fmt tool (not to be confused with the fmt package) instead.
When you write code, most likely, someone, even if it’s just you are going to read that code later and need to understand what it’s doing. There are lots of ways to format your code and to solve a particular problem when programming. In fact, the motto of the Perl programming language is “There’s more than one way to do it.”
Following a style guide makes your programs more readable and maintainable. When everyone follows a consistent style, someone can look at a piece of code and not need to try to decipher the specific style of the programmer instead of just looking at the logic of the program. One of the most common complaints about Perl from developers is that it’s hard to understand precisely because of the situation embodied by its motto.
The Go Style Guide
There isn’t a formal Go style guide. However, the Go community does have a few resources that form part of an informal style guide. The first resource is the language syntax specification itself. While there is not a formal Go style guide there is a formal definition of the language syntax. This specification outlines the entire Go programming language and its usage.
The Second resource that serves as part of the Go style guide is the Effective Go document. This document describes the best practices for writing quality Go code. Effective Go is less focused on particular style and more focused on the function of your Go code itself. The Go community refers to Code written to follow the guidance of Effective Go as idiomatic code.
The Go fmt Tool
The Go fmt tool is the official replacement for a formal style guide. Instead of writing a document that describes how to format Go code the Go project created the Go fmt tool to format your code automatically. In addition to making your code more consistent and thus readable, this makes it easier for other programs to parse your code. For example, programs called “linters” or code analyzers that try to find bugs in your code for you.
csotherden-mba:switch sloth$ go fmt main/main.go
The go fmt tool is a sub command of the “go” program and expects the name of Go code that you want to format. The tool will reformat and save the code in the provided file.