liveBook · Manning

Gofmt

As explained in Go in Practice, Second Edition

go fmt is a Go command that reformats Go source files according to the language's canonical formatting style.

Use `go fmt` to keep Go source in a consistent style before sharing it. It is an alias for the separate `gofmt` tool, which offers additional options. Make formatting part of your normal coding workflow rather than a cleanup task at the end. section 6.1.1

A practical formatting loop:

  • Run `go fmt` in the directory containing the files you want to format. An IDE can also format on save. section 1.5 section 6.1.1
  • To inspect proposed changes without changing a file, run `gofmt -d myfile.go`. Version control can help review or undo applied changes. section 6.1.1
-- myfile.go.orig
+++ myfile.go
@@ -1,16 +1,13 @@
-
-
 package main

 import "fmt"
 import "os"

-
 func main() {
-    fmt.Println(  "checking for environment variable 
CLEANUP")                                                            #1
-
-        if envvar := os.GetEnv("CLEANUP"); envvar != "" {
-            fmt.Println(" did not find it, value is:", envvar);     #2
-        }
+    fmt.Println("checking for environment variable 
CLEANUP") #3
+
+    if envvar := os.GetEnv("CLEANUP"); envvar != "" {
        fmt.Println(" did not find it, value is:", env
        var)                                              #4
+    }

}

The diff shows excess spaces and blank lines removed, indentation made consistent, and unnecessary semicolons dropped. Formatting still leaves some choices, such as separate import declarations, to the developer. section 6.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Shows a before-and-after diff and a preview command, while leaving some newline and import-declaration choices to developers.
Examples
Uses a poorly formatted Go file and a `gofmt -d` diff showing whitespace, indentation, and semicolon changes.
What it assumes
Assumes familiarity with Go source files and command-line tools; illustrates formatting through a concrete diff.
What you can do after
Operate/configure it by running `go fmt`, previewing changes with `gofmt -d`, or enabling IDE formatting.
How it connects
Connects formatting to Go imports, version control, and IDE format-on-save workflows.

Also explained in

Compare how 3 books explain gofmt →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.