How to Use go fmt: Format Go Code Easily
Use
go fmt to automatically format your Go source files with standard style. Run go fmt followed by file or directory names in your terminal to fix indentation, spacing, and layout.Syntax
The basic syntax of go fmt is simple. You run it in your terminal followed by the files or directories you want to format.
go fmt: formats all Go files in the current directory.go fmt filename.go: formats a specific file.go fmt ./...: formats all Go files recursively in the current directory and subdirectories.
bash
go fmt [files or directories]
Example
This example shows how to format a Go file named main.go. Suppose the file has inconsistent spacing or indentation.
Run go fmt main.go in your terminal. It will rewrite the file with proper formatting automatically.
go
package main import "fmt" func main() { fmt.Println("Hello, Go fmt!") }
Output
Hello, Go fmt!
Common Pitfalls
Some common mistakes when using go fmt include:
- Running
go fmton non-Go files, which does nothing. - Expecting
go fmtto fix code logic errors—it only formats style. - Not saving files before running
go fmt, so changes are not applied.
Always ensure your files are saved and are valid Go source files before formatting.
bash
/* Wrong usage example: */ // Running go fmt on a text file does nothing /* Right usage example: */ // Run go fmt on .go files to fix formatting // go fmt main.go
Quick Reference
Here is a quick cheat sheet for go fmt commands:
| Command | Description |
|---|---|
| go fmt | Format all Go files in current directory |
| go fmt filename.go | Format a specific Go file |
| go fmt ./... | Format all Go files recursively in current directory and subdirectories |
| go fmt -n | Print commands that would be executed without running them |
| go fmt -x | Print commands as they are executed |
Key Takeaways
Run go fmt in your terminal to format Go source files automatically.
Use go fmt with file or directory names to target specific code.
go fmt only changes code style, not logic or errors.
Save your files before running go fmt to apply formatting.
Use go fmt ./... to format all Go files recursively in a project.