Knaph

gofmt

Go shipped with a formatter on day one and the whole ecosystem adopted it. That means no per-project style config to negotiate, no black vs. autopep8 decision, and no tabs-versus-spaces thread in code review. (It's tabs. It's settled. It isn't configurable.) Every Go file you'll ever read is laid out the same way, so your eye stops spending effort on it.

Two commands, one engine:

  • gofmt is the formatter. Give it files or directories; by default it prints the result and changes nothing.
  • go fmt wraps it as gofmt -l -w over packages, so it needs a go.mod. You don't have one yet — until then, name files directly.
gofmt -d main.go    # show what it would change, as a diff
gofmt -w main.go    # rewrite the file in place
gofmt -l .          # list files that need formatting - the CI check

The file below compiles and runs exactly as written. Go is insensitive to this whitespace, which is precisely why it can be normalized mechanically:

Before gofmt
package main
 
import "fmt"
 
func main(){
x:=3
y := 4
if x<y {
fmt.Println("x is smaller" )
}
}
After gofmt
package main
 
import "fmt"
 
func main() {
	x := 3
	y := 4
	if x < y {
		fmt.Println("x is smaller")
	}
}

Indentation by tabs, one space on each side of := and <, ){ opened up to ) {, and the stray space before ) dropped. All of it is layout — gofmt never changes what your program does.

One useful side effect: gofmt has to parse your file, so it refuses to touch one with a syntax error. If gofmt won't format it, it won't compile either.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude