I see that there is both gofmt
and go fmt
. What is the difference between gofmt & go fmt?
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.
gofmt read the go program and show the result after indentation, vertical alignment and even re formats comments too. gofmt filename : This will print reformatted code. gofmt -w filename : This will reformat the code and updates the file.
Gofmt formats Go programs. It uses tabs for indentation and blanks for alignment. Alignment assumes that an editor is using a fixed-width font.
Run go help fmt
to see the difference. In short, go fmt
runs gofmt -l -w
on the packages specified by the arguments.
The -w
flag writes the result back to the source file. The -l
flag prints the name of modified files.
The arguments to go fmt
are packages (run go help packages
for a description). The arguments to gofmt
are file system paths.
Here are some examples showing how the arguments are handled differently:
gofmt -w . # formats files in current directory and all sub-directories
go fmt ./... # similar to previous
go fmt . # formats files in current package
gofmt -w foo/bar # formats files in directory $PWD/foo/bar and sub-dirs
go fmt foo/bar # formats files in directory $GOPATH/src/foo/bar
gofmt -w # error, no file or directory specified
go fmt # formats files in current package
The gofmt command will process the files given as arguments. The go fmt tool runs gofmt on all the files in the package paths given as arguments. Thus if I am in the encoding/gob directory,
gofmt decode.go
will format the single file decode.go, while the tool run
go fmt .
(. is actually the default) will format all the files in the encoding/gob package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With