Go tools
With gofmt, you can format Go source code in the opened file or in the whole Go project.
For a single file, you can use the built-in import management and code formatter. Imports are managed on-the-fly. To customize import management, open settings by pressing CtrlAlt0S and navigate to Languages & Frameworks | Go | Imports. .
To reformat code, press CtrlAlt0L. Comparing to gofmt, IntelliJ IDEA’s formatter works with syntactically incorrect code and can be invoked on an arbitrary block. There are other features such as automatically inserting semicolons, wrapping parameters and arguments, and others.
Also, you can use On Reformat Code action option (Editor | Code Style | Go, click Other tab). This option lets you invoke both formatters by pressing CtrlAlt0L whenever you want.
Alternatively, use the Reformat code option in Actions on Save. This action is enabled by default for IntelliJ IDEA. When triggered by pressing Ctrl0S, the IDE runs the built-in IntelliJ IDEA formatter and gofmt.
To format code in the opened file, go to Tools | Go Tools | Go fmt file.
To format code in the current project, go to Tools | Go Tools | Go fmt project.
To format code before you commit your changes into VCS, select the Go fmt checkbox. For more information about committing your changes, refer to Commit and push changes to Git repository.
tip
For more information about
gofmt
, refer to Command gofmt.
With goimports, you can automatically update your Go import lines (add missing and remove unreferenced imports).
If your project does not have goimports, click the go get goimports link in the Goimports file notification window. Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports:
go get golang.org/x/tools/cmd/goimports
. Press Enter.To add missing imports, navigate to Tools | Go Tools and click Goimports file.
tip
The goimports tool also formats your code in the same style as
gofmt
. For more information aboutgoimports
, refer to Command goimports.
The go generate
uses the //go:generate
directive to define and invoke the code generation. For more information about go generate
, refer to Generating code at blog.golang.org.
Add the following line to your Go code:
//go:generate command arguments
(for example,//go:generate stringer -type=Pill
)Click Tools | Go Tools | Go generate file. Alternatively, click the Run icon () on the gutter and select Go Generate.
tip
For more information about
go generate
, refer to Generate Go files by processing source and Generating code.
The go vet
command examines Go source code and reports suspicious constructs.
To find possible bugs or suspicious constructs with
go vet
, click Tools | Go Tools | Go vet file. You can see the result of code analysis in the Terminal tool window.
tip
For more information about
go vet
, refer to Command vet.