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:
gofmtis the formatter. Give it files or directories; by default it prints the result and changes nothing.go fmtwraps it asgofmt -l -wover packages, so it needs ago.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 checkThe file below compiles and runs exactly as written. Go is insensitive to this whitespace, which is precisely why it can be normalized mechanically:
package main
import "fmt"
func main(){
x:=3
y := 4
if x<y {
fmt.Println("x is smaller" )
}
}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.