Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between gofmt & go fmt?

Tags:

go

I see that there is both gofmt and go fmt. What is the difference between gofmt & go fmt?

like image 896
codefx Avatar asked Mar 23 '19 23:03

codefx


People also ask

What is Gofmt Golang?

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.

How do I use Gofmt?

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.

Does go FMT use tabs?

Gofmt formats Go programs. It uses tabs for indentation and blanks for alignment. Alignment assumes that an editor is using a fixed-width font.


Video Answer


2 Answers

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
like image 86
Bayta Darell Avatar answered Oct 21 '22 07:10

Bayta Darell


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.

like image 45
Luis Cardoza Bird Avatar answered Oct 21 '22 07:10

Luis Cardoza Bird