The Analogy: One Engraving Standard
Put ninety musicians in a room with a score none of them has seen and they will play it correctly on the first pass. That is only possible because music notation is standardized to an almost fussy degree. Note heads are filled or hollow, stems turn up below the middle line and down above it, dynamics sit under the staff, tempo sits above it, and the horizontal spacing of the notes carries information about rhythm. None of this is up to the person writing the parts out. An engraver who invented a personal style would not be expressive, they would be unreadable.
Imagine the alternative. Every composer chooses their own notation: one writes rests as small triangles, another puts dynamics above the staff, a third indents each bar to show phrasing. The music is unaffected, all of it is perfectly playable in principle, and rehearsal collapses into decoding. The first hour goes on learning the notation rather than the piece. Standard engraving is not aesthetically superior to the alternatives. It is superior because it is shared, and being shared is worth more than being right.
Go's toolchain applies this to source code, and gofmt is the engraving standard. It reads your file and rewrites it into the canonical form, and it takes no options at all. You do not get to prefer two spaces, or braces on their own line, or a different way of aligning struct fields, because the entire value of the thing is that nobody gets to prefer anything. go vet is the conductor who hears a wrong accidental that was technically written correctly, and go mod is the orchestra tuning to concert A so that every part agrees on which version of the piece it is playing.
What you get in exchange is quiet. Code review discusses the code. A diff shows changes in meaning, not changes in whitespace, because whitespace is not a variable. A new engineer opens an unfamiliar repository and it looks exactly like the last one, so the layout is invisible and only the logic stands out. This lesson is about the rules the toolchain enforces and the small number of things it will never fix for you.
Syntax or Core Structure
Start with a file that is legal Go and formatted by hand, badly:
// messy.go
package main
import ("fmt"
"strings")
func main(){
name := "go"
greeting:=strings.ToUpper( name )
if greeting=="GO" { fmt.Println("greeting:",greeting) }
}
That compiles. It is also unreadable in a way no team should have to negotiate about, so nobody negotiates:
gofmt -l . # list files that are not in canonical form
gofmt -w messy.go # rewrite the file in place
gofmt -l . # nothing left to report
Output:
messy.go
The first gofmt -l names the offending file, and the third prints nothing at all, which is the signal that there is nothing left to say. This is the whole interface: silence means correct. Here is what the file became:
// messy.go
package main
import (
"fmt"
"strings"
)
func main() {
name := "go"
greeting := strings.ToUpper(name)
if greeting == "GO" {
fmt.Println("greeting:", greeting)
}
}
Six things changed, and none of them were optional. A blank line was inserted after the package clause and between top level declarations. The import group was broken onto one line per path. The extra spaces around := and inside ToUpper( name ) were removed, while a single space was added around ==. The single line if body was expanded onto its own lines. And the indentation became a tab, not spaces. The code samples on this page use spaces so they line up in a browser, but gofmt writes a tab character and aligns continuation columns with spaces, which is why Go code looks correct at any tab width your editor prefers.
Technical Depth: The Rules Behind the Rewrite
Semicolons Exist, You Just Do Not Type Them
Go's grammar requires semicolons as statement terminators. The scanner inserts them for you using two rules, and understanding those two rules explains the one syntax error that catches every newcomer.
A semicolon is inserted at the end of a line when the final token is an identifier, a literal, one of break continue fallthrough return, one of ++ --, or one of ) ] }. A semicolon is also inserted before a closing ) or } so that you may omit the last one in a list.
| You write | Scanner sees | Result |
|---|---|---|
x := 1 | x := 1; | Fine |
func main() { | no insertion after { | Fine |
func main() then { on the next line | func main(); then { | Syntax error |
return then x on the next line | return; then x | Compile error if the function declares a result |
This is why the brace must be on the same line. It is not a style rule that gofmt enforces, it is a consequence of the grammar, and it is the reason gofmt cannot fix that particular mistake for you: by the time the file is parsed the meaning has already changed.
What gofmt Standardizes, and What It Leaves Alone
| Decided for you | Still yours |
|---|---|
| Indentation with tabs | Names of everything |
| Spacing around operators and after commas | How you group imports into blocks |
| One import path per line inside a group | Whether to use var or := |
| Alignment of adjacent struct fields and comments | Order of your declarations |
| Blank line after the package clause and between declarations | Where you put blank lines inside a function |
| Removal of trailing whitespace | Line length, which has no limit |
Placement of else on the closing brace line | Whether a comment is worth writing |
The second column matters. gofmt is a formatter, not a linter and not a reviewer. It will happily format a badly named variable inside a function that is far too long.
goimports: The Version Everyone Actually Runs
goimports is gofmt plus import management. It adds the import you just started using, removes the one you stopped using, and splits imports into groups with the standard library first.
go install golang.org/x/tools/cmd/goimports@latest
goimports -w .
import (
"encoding/json" // standard library, first group
"fmt"
"github.com/example/store" // third party, second group
)
Because an unused import is a compile error in Go, running this on save turns a whole category of build failure into something you never see happen.
go vet Finds the Legal Mistakes
The compiler proves your program is well formed. go vet reports the constructs that are well formed and still wrong.
| Check | Catches |
|---|---|
printf | A format verb that does not match its argument, or a missing argument |
copylocks | Passing a value that contains a sync.Mutex by copy |
loopclosure | A goroutine in a loop capturing the loop variable unsafely |
shadow | An inner declaration hiding an outer one, with the analyzer enabled |
structtag | A malformed or duplicated struct tag |
unusedresult | Discarding the result of fmt.Sprintf or errors.New |
nilfunc, unmarshal, atomic | Comparisons and calls that can never do what was intended |
go test runs a subset of these automatically before compiling your tests, which is why a broken Printf sometimes surfaces the moment you run the test suite.
Naming Is the Part the Tools Cannot Do
Go has strong naming conventions, and one of them is not a convention at all: the case of the first letter decides whether an identifier is visible outside its package.
| Rule | Correct | Wrong |
|---|---|---|
| Exported means capitalized | func Parse() | func parse() used from another package |
| MixedCaps, never underscores | maxRetryCount | max_retry_count |
| Package names are short, lowercase, no plural | package store | package storeUtils |
No Get prefix on accessors | u.Name() | u.GetName() |
Interfaces of one method end in -er | Reader, Formatter | IReader, ReaderInterface |
| Receivers are one or two letters | func (s *Server) | func (this *Server) |
Error values start with Err | ErrNotFound | NotFoundError as a value |
| Error strings are lowercase, no final period | errors.New("record not found") | errors.New("Record not found.") |
The error string rule exists because errors get wrapped: your message ends up in the middle of a longer sentence, and a capital letter halfway through a line of log output is noise.
Doc comments are also conventional rather than syntactic. A comment immediately above a declaration, starting with the identifier's own name, becomes its documentation:
// Tally counts word frequencies in text and returns them ordered by
// descending count, breaking ties alphabetically.
func Tally(text string) []Count { ... }
Real World Example: A Formatter You Can Call Yourself
gofmt is not a magic binary. It is a thin wrapper around go/format, a package in the standard library, which means your own program can decide whether a file is canonical. This is how editor plugins, code generators and CI checks all work, and writing it once removes the mystery.
package main
import (
"fmt"
"go/format"
"strings"
)
const messy = `package main
import "fmt"
func main(){
x:=1
fmt.Println( x )
}
`
func main() {
canonical, err := format.Source([]byte(messy))
if err != nil {
fmt.Println("not parseable:", err)
return
}
fmt.Println("already canonical:", string(canonical) == messy)
fmt.Println("indented with tabs:", strings.Contains(string(canonical), "\t"))
fmt.Println("lines before:", strings.Count(messy, "\n"))
fmt.Println("lines after:", strings.Count(string(canonical), "\n"))
fmt.Println("--- canonical form, tabs shown as >> ---")
fmt.Print(strings.ReplaceAll(string(canonical), "\t", ">>"))
}
Output:
already canonical: false
indented with tabs: true
lines before: 6
lines after: 8
--- canonical form, tabs shown as >> ---
package main
import "fmt"
func main() {
>>x := 1
>>fmt.Println(x)
}
The comparison on the third line of main is the entire CI check, expressed in one expression. If format.Source returns something different from what it was given, the file is not canonical, and a build gate can refuse the change without a human having to notice. Real projects run gofmt -l . and fail when the output is non empty, which is the same test written as a shell command: a list of file names means somebody skipped the formatter.
The two blank lines that appeared are worth dwelling on, because they show that gofmt is not doing textual cleanup. It parsed the file into a syntax tree, threw the original whitespace away, and printed the tree according to fixed rules. That is why it can never produce a differently behaving program, and also why it cannot repair a brace on the wrong line: a file that does not parse has no tree to print. format.Source returns an error in that case, which is what the err branch is for.
The tab is not a preference either, it is a division of labor. gofmt indents structure with tabs and aligns columns within a line using spaces, so your editor's tab width changes how deeply the code appears nested without ever breaking the alignment of adjacent struct fields or trailing comments. Teams that argue about two spaces against four are arguing about a setting Go moved into the viewer.
Being able to call the formatter as a library is also why code generation is unremarkable in Go. A generator emits roughly formatted source, pipes it through format.Source, and writes out something indistinguishable from hand written code, which then reviews as normal code in a normal diff. The pattern appears throughout the ecosystem: stringer, protocol buffer plugins and mocking tools all end with the same call you just made.
Common Mistakes
- Putting the opening brace on its own line. This is not a style violation, it is a syntax error caused by automatic semicolon insertion. The compiler message points at the brace and can look baffling until you know why.
- Treating
gofmtas optional and formatting by hand. The cost is not ugly code, it is diffs full of whitespace changes that hide the one line that actually changed. Configure format on save on day one.
- Expecting
gofmtto sort your imports. It formats the groups you wrote but will not add, remove or regroup paths. That isgoimports, and it is the tool you actually want bound to save.
- Using underscores or ALL_CAPS in names. Go has no separate constant naming convention: an exported constant is
MaxRetries, notMAX_RETRIES. Screaming case marks code as translated from another language.
- Naming an interface
IStoreor a receiverthis. Both compile and both immediately tell a reviewer that the author is writing Java or C# with Go syntax. UseStoreands.
- Capitalizing error strings or ending them with a period. Wrapped errors concatenate, so
failed to open file: Record not found.reads as a mistake in the middle of a log line.
- Assuming a capital letter is only a convention. Rename
Parsetoparseand every other package loses access to it. Export deliberately, because an exported identifier is a promise you have to keep.
- Skipping
go vetbecause the code compiles.fmt.Printf("%d items", name)compiles, ships, and prints garbage. Vet catches it in the second it takes to run.
- Fighting the lack of a line length limit. Go has none, and
gofmtwill not wrap for you. Break long lines where the logic has a seam, not at an arbitrary column.
Best Practices
- Bind
goimportsto save in your editor and never format Go by hand again. - Add
gofmt -l .to CI and fail the build when its output is not empty, so formatting is never a review comment. - Run
go vet ./...in the same CI step as your tests, and treat any output as a failure. - Name things for the caller's benefit:
store.Getreads better thanstore.GetItemFromStore. - Keep package names short and let the qualified name carry the meaning, so
http.Serverrather thanhttp.HTTPServer. - Write doc comments that start with the identifier's own name, because that is what
go docand every editor tooltip will show. - Export the smallest surface that does the job, then widen it later if a caller genuinely needs more.
- Let the tools be boring. Any minute spent configuring formatting in Go is a minute spent undoing the language's main gift.
Practice Exercises
- Break the Scanner: Write a file with
func main()and{on separate lines and record the compiler's exact message. Then explain in one sentence, using the semicolon insertion rules, why the message mentions a token you did not type.
- Watch the Tree Get Rebuilt: Take a small file and mangle only its whitespace: collapse the imports onto one line, remove the blank lines, add extra spaces inside every call. Run
gofmt -don it and confirm the diff restores exactly the original. Explain why the result is guaranteed to behave identically.
- Catch a Bug the Compiler Allows: Write a program with
fmt.Printf("%d\n", "hello")and confirm that it builds and runs. Then rungo vetand record what it says. Addgo vet ./...to a script namedcheck.shalongsidegofmt -l .andgo test ./....
- Rename for Export: Write a two package module where package
maincalls a function in packagestore. Lowercase the function's first letter, observe the failure, and write down the error. Then add a doc comment in the canonical form and confirmgo doc ./storeprints it.