Format Go source code with gofmt
Why format source?
gofmt is the Go toolchain formatter. It applies a consistent layout to valid Go source, making indentation and spacing easier to read. It does not repair every syntax or type error. This deliberately untidy example is valid Go.
Without -w, gofmt prints formatted source to standard output. With -w, it writes the result back to the file. The formatted file looks like the following.
Check that the program still works
Run go run main.go before and after formatting. Both versions print Go. Keep formatting separate from behavioral changes so differences are easier to review. A file that gofmt accepts can still contain type errors; formatting is not type checking.
Try it locally
Use the untidy example, change Go to Clean, run gofmt -w main.go, then execute the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Getting Started 09: Format Go source code with gofmt
Check the lesson objective before moving on.
Which command writes the formatting back to main.go?
What does gofmt success establish?