Introduction
Gofmt is a tool that automatically formats Go source code.
Gofmt’d code is:
- easier to write: never worry about minor formatting concerns while hacking away,
- easier to read: when all code looks the same you need not mentally convert others’ formatting style into something you can understand.
- easier to maintain: mechanical changes to the source don’t cause unrelated changes to the file’s formatting; diffs show only the real changes.
- uncontroversial: never have a debate about spacing or brace position ever again!
Format your code
We recently conducted a survey of Go packages in the wild and found that about 70% of them are formatted according to gofmt’s rules. This was more than expected - and thanks to everyone who uses gofmt - but it would be great to close the gap.
To format your code, you can use the gofmt tool directly:
$ gofmt -w yourcode.go
Or you can use the “go fmt” command:
$ go fmt path/to/your/package
To help keep your code in the canonical style, the Go repository contains hooks for editors and version control systems that make it easy to run gofmt on your code.
Format all files in a directory (including sub directories). You can put this in a git commit hook to run it every time you commit.
$ go fmt ./...
Git’s Pre-commit
Reference
- https://pkg.go.dev/cmd/gofmt
- https://blog.golang.org/gofmt
- https://stackoverflow.com/questions/47735678/goland-how-to-use-gofmt
- https://www.jetbrains.com/help/go/integration-with-go-tools.html
FEATURED TAGS
algorithm
algorithmproblem
architecturalpattern
architecture
aws
c#
cachesystem
codis
compile
concurrentcontrol
database
dataformat
datastructure
debug
design
designpattern
distributedsystem
django
docker
domain
engineering
freebsd
git
golang
grafana
hackintosh
hadoop
hardware
hexo
http
hugo
ios
iot
java
javaee
javascript
kafka
kubernetes
linux
linuxcommand
linuxio
lock
macos
markdown
microservices
mysql
nas
network
networkprogramming
nginx
node.js
npm
oop
openwrt
operatingsystem
padavan
performance
programming
prometheus
protobuf
python
redis
router
security
shell
software testing
spring
sql
systemdesign
truenas
ubuntu
vmware
vpn
windows
wmware
wordpress
xml
zookeeper