Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

goland how to use gofmt?

Tags:

go

goland

I started learning golang and installed GoLand from JetBrains. I am reading the book The Go Programming Language, and in the first chapter author strongly recommends using the gofmt tool before each save. How I can follow this recommendation in GoLand?

like image 805
Mikita Melnikau Avatar asked Dec 10 '17 03:12

Mikita Melnikau


People also ask

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.

Does go use tabs or spaces?

As mentioned on IRC already, Go doesn't use 8-space indents, it uses a tab.


2 Answers

There are ways to format your code , you can do that by using any one of the way :

  1. once your code is done. just run the command " gofmt -s -w ." in terminal in required directory or else in needed file. it will format your whole directory/file as per your need .
  2. go to preferences ->Tools ->File Watchers and enable go fmt . This way on each save it will format the file.
like image 148
negi Yogi Avatar answered Sep 21 '22 07:09

negi Yogi


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.

like image 22
Arman Ordookhani Avatar answered Sep 18 '22 07:09

Arman Ordookhani