Skip to main content
Gofmt is the official Go code formatter. It formats Go programs with consistent style, using tabs for indentation and blanks for alignment.

Overview

Gofmt enforces a standard formatting style across all Go code, eliminating debates about code style and ensuring consistency. Most Go code in the wild is formatted with gofmt.
Using gofmt is considered a best practice in the Go community. Most editors can be configured to run gofmt automatically on save.

Usage

gofmt [flags] [path ...]
Without an explicit path, gofmt processes standard input. Given a file, it operates on that file; given a directory, it operates on all .go files in that directory, recursively.

Flags

Output Flags

-d
flag
Print diffs to standard output instead of reformatted sources. Shows what changes would be made.
-l
flag
List files whose formatting differs from gofmt’s. Does not print reformatted sources.
-w
flag
Write result to source file instead of standard output. Overwrites files in-place with gofmt’s version.

Code Transformation Flags

-r
string
Apply the rewrite rule to source before reformatting.Format: pattern -> replacementBoth pattern and replacement must be valid Go expressions.
-s
flag
Simplify code (after applying rewrite rule, if any). Applies various simplifications to the code.

Other Flags

-e
flag
Print all errors (including spurious ones).
-cpuprofile
filename
Write CPU profile to the specified file (for debugging gofmt performance).

Common Usage Patterns

1

Check Formatting

List all files that need formatting:
gofmt -l .
This is useful in CI/CD pipelines to verify code is formatted.
2

Format Files

Format all Go files in current directory and subdirectories:
gofmt -w .
The -w flag writes changes directly to files.
3

Preview Changes

See what changes gofmt would make without modifying files:
gofmt -d file.go
Shows a unified diff of the changes.

Examples

Basic Formatting

# Format and print to stdout
gofmt file.go

# Format and overwrite file
gofmt -w file.go

# Show diff without modifying
gofmt -d file.go

Rewrite Rules

The -r flag enables powerful code transformations using pattern matching:
# Check for unnecessary parentheses
gofmt -r '(a) -> a' -l *.go

# Remove unnecessary parentheses
gofmt -r '(a) -> a' -w *.go
In rewrite patterns, single-character lowercase identifiers (like α, β, a, b) serve as wildcards matching arbitrary sub-expressions.

Simplification with -s

The -s flag applies various simplifications:
// Composite literals
[]string{string("foo"), string("bar")}

// Slice expressions
s[a:len(s)]

// Range loops
for x, _ = range v {...}
for _ = range v {...}
Apply simplifications:
gofmt -s -w .

Integration with Editors

VS Code

The Go extension automatically runs gofmt on save. Configuration in settings.json:
{
  "go.formatTool": "gofmt",
  "editor.formatOnSave": true
}

Vim/Neovim

Using vim-go plugin:
" Auto-format on save
let g:go_fmt_autosave = 1
let g:go_fmt_command = "gofmt"

Emacs

;; Auto-format on save
(add-hook 'before-save-hook 'gofmt-before-save)

CI/CD Integration

Checking Formatting in CI

# .github/workflows/ci.yml
- name: Check formatting
  run: |
    unformatted=$(gofmt -l .)
    if [ -n "$unformatted" ]; then
      echo "The following files are not formatted:"
      echo "$unformatted"
      exit 1
    fi

go fmt vs gofmt

The go fmt command is a wrapper around gofmt:
CommandDescription
gofmtStandalone tool, formats files or directories
go fmtWrapper that runs gofmt -l -w on packages
# These are equivalent:
go fmt ./...
gofmt -l -w .
Use go fmt for package-based formatting and gofmt when you need more control over flags and output.

Formatting Standards

What gofmt Does

  • Uses tabs for indentation
  • Uses blanks for alignment
  • Removes trailing whitespace
  • Ensures consistent spacing around operators
  • Formats comments properly
  • Aligns struct field declarations
  • Formats function parameters consistently

What gofmt Doesn’t Do

  • Doesn’t enforce line length limits
  • Doesn’t reorganize imports (use goimports for that)
  • Doesn’t add or remove blank lines between functions
  • Doesn’t rename variables or functions

Advanced Usage

Formatting Fragments

Gofmt can format Go fragments (not just complete programs):
# Format a code snippet from stdin
echo 'func f(){println("hello")}' | gofmt
Output:
func f() { println("hello") }

Processing Multiple Files

# Format specific files
gofmt -w file1.go file2.go file3.go

# Format all Go files in current directory (not recursive)
gofmt -w *.go

# Format all Go files recursively
find . -name '*.go' -exec gofmt -w {} \;

Performance

Gofmt is designed to be fast:
  • Typically processes thousands of lines per second
  • Can be parallelized across multiple files
  • Uses efficient parsing and formatting algorithms
For very large codebases, consider using gofumpt (a stricter formatter) or running gofmt in parallel across directories.

Troubleshooting

Common Issues

Your editor may be using a different formatter (like goimports or gofumpt). Check your editor’s Go extension settings.
Gofmt only handles formatting, not style issues. Use go vet and linters like golangci-lint for additional checks.
Gofmt requires valid Go syntax. Fix syntax errors first, then run gofmt.

See Also

go Command

Overview of the go command

Building Programs

Building Go applications

References

Build docs developers (and LLMs) love