Linux command
gofmt 命令
文件
复制后可按需替换文件名、目录或参数。
常用示例
Format a Go file
gofmt [file.go]
Format and overwrite
gofmt -w [file.go]
Format all Go files
gofmt -w [path/to/directory]
Show diff of formatting
gofmt -d [file.go]
List files that would be
gofmt -l [path/to/directory]
Simplify code
gofmt -s [file.go]
Format and simplify
gofmt -s -w [file.go]
说明
gofmt formats Go source code according to standard Go style guidelines. It uses tabs for indentation and blanks for alignment, ensuring consistent formatting across all Go codebases. When invoked without paths, it reads from standard input. With file or directory arguments, it processes those paths recursively. The -s flag applies simplification transformations like removing unnecessary type declarations. The -r flag enables custom rewrite rules for code transformations.
参数
- -w
- Write result to source file instead of stdout.
- -d
- Display diffs instead of rewriting files.
- -l
- List files whose formatting differs from gofmt's.
- -s
- Simplify code (apply simplification rules).
- -e
- Report all errors (not just first 10 per file).
- -r _RULE_
- Apply rewrite rule (e.g., 'ab:len(a) -> ab:').
FAQ
What is the gofmt command used for?
gofmt formats Go source code according to standard Go style guidelines. It uses tabs for indentation and blanks for alignment, ensuring consistent formatting across all Go codebases. When invoked without paths, it reads from standard input. With file or directory arguments, it processes those paths recursively. The -s flag applies simplification transformations like removing unnecessary type declarations. The -r flag enables custom rewrite rules for code transformations.
How do I run a basic gofmt example?
Run `gofmt [file.go]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does -w do in gofmt?
Write result to source file instead of stdout.