liveBook · Manning

Gofmt

As explained in Go in Action, Second Edition

gofmt is the standard Go source-code formatter that applies the official Go formatting style.

gofmt is Go’s built-in source formatter. It parses Go code and rewrites it with consistent indentation, spacing, and alignment, producing one standard layout regardless of the programmer’s preferences. section 1.6 section 2.4.4

The design deliberately removes configuration and style debates. Standard formatting lowers the cognitive load of reading unfamiliar code and makes formatting a shared engineering convention rather than a review topic. section 1.6 section 2.4.4

Use gofmt in two practical modes:

  • Run `gofmt -d main.go` to inspect a diff without changing the file. section 2.4.4
  • Run `gofmt -w main.go` to rewrite the file in place. section 2.4.4
  • Let an editor or IDE invoke gofmt on save, then use the diff mode when checking whether formatting is already standard. section 2.4.4

Checking a Go file

Given a file named `main.go`, run `gofmt -d main.go`. No output means the file already matches the standard format. A diff identifies changes such as indentation and spacing before any rewrite is applied. section 2.4.4

Listing 2.6 Testing your formatting with gofmt
$ gofmt -d main.go

Inspect the command used to test whether `main.go` follows standard Go formatting. section 2.4.4

How Go in Action, Second Edition covers it

How deep it goes
Explains parsing, rewriting, formatting modes, and editor use, but does not descend into formatter implementation internals.
Examples
Demonstrates `gofmt -d main.go`, its sample diff, and `gofmt -w main.go` for in-place rewriting.
What it assumes
Assumes a Go source file and Go distribution, while teaching the formatting workflow and its rationale from the tool’s basic purpose.
What you can do after
Operate/configure it via `gofmt -d` for inspection and `gofmt -w` for direct file rewriting.
How it connects
Connects source formatting with code review, editor integration, standardized tooling, and Go’s broader build and development workflow.

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 Action, Second Edition. The section links point to the parts of the book it draws on.