goland how to use gofmt?
You can do that in one of these two ways:
For Goland: preferences ->Tools ->File Watchers and enable
go fmt
. This way on each saves it will format the file.once your code is done. just run the command
gofmt -s -w .
in the terminal in the required directory or else in the needed file. it will format your whole directory/file as per your need.
GoLand have commands to go fmt
your file or project. Right click on your file and you will find it under "Go tools". You could see its shortcut there.
You can also use "Reformat code" command (bound to Command-Alt-L for me). It's not 100% same as go fmt
but very close. Also works for other languages.
If you have an open terminal, you can run go fmt ./...
to 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.
As others mentioned there's a file watcher section under Preferences → Tools → File Watchers, in there you can setup to run go fmt
or goimports
everytime you save a Go file.
Just want to add 1 more option. You can automatically apply go fmt every time when you are about to commit to git. When you open the commit window, under the Before Commit
section, there is a Go fmt
checkbox. Just check it. Later when you do another commit, the default value for that checkbox is checked. So, you only need to check it once. Then go fmt will run automatically before you commit.