पाठ 23 / 26
gofmt and Consistent Style
One style, applied by a tool.
No style debates
gofmt (and go fmt) rewrites code into the one standard Go style: tabs for indentation, aligned spacing, consistent braces. Because every Go project uses it, code looks the same everywhere and reviews focus on substance. Editors run it on save; CI can check with gofmt -l (list unformatted files). goimports also adds and removes imports.
What gofmt changes, run
I ran this with Go 1.27.1 (gofmt -d main.go | tail -n +4 in a module named demo, standard library only). gofmt -d shows the diff it would apply to a cramped file: blank lines between declarations, spaces around operators, and indented, braced blocks. The diff headers were trimmed.
package main
import "fmt"
func main(){
x:=[]int{1,2,3}
for _,v:=range x{fmt.Println(v)}
}
Output:
@@ -1,6 +1,10 @@
package main
+
import "fmt"
-func main(){
-x:=[]int{1,2,3}
-for _,v:=range x{fmt.Println(v)}
+
+func main() {
+ x := []int{1, 2, 3}
+ for _, v := range x {
+ fmt.Println(v)
+ }
}Format on save
Configure your editor to run gofmt or goimports on save so formatting never appears in reviews.
त्वरित जाँच: Why does every Go project use gofmt?
- It enforces one standard style automatically, ending style debates
- It makes code run faster
- It is required to compile
- It removes comments
Answer
It enforces one standard style automatically, ending style debates — Consistency at zero cost.