The first linter you face coming into Go is go vet. It is a built-in linter targeted mostly at finding bugs rather than code style.
Another official linter from the Go core team is golint. This one is targeted at finding not bugs but mostly style issues from the official code review guide and effective go.
If you want to catch more bugs and write more effective code, consider running more linters. Go has plenty of them. Of course, it would be hard to download, install, and run all of them. Luckily, we have amazing golangci-lint. It is a wrapper, providing a single unified way to run and configure more than 40 linters. Keep in mind that by default, it runs only a few of them, so it’s good to have an explicit configuration with a listing of all linters you want to use in the project. And if you’d like to know from what you can start, below are some most notable linters.
A few biggest linters:
A few more specific but helpful linters:
err
variable but forgot to check it.Useful linters without golangci-lint integration (yet?):
What should you use? Everything you can! If you have an existing project, enable all linters that are easy to integrate, and then slowly, one by one, try and enable all that look reasonable and helpful. Just give it a try! Also, be mindful of your coworkers, help them to fix a code that a linter complains about, and be ready to disable a check if it works not so well for your codebase, especially if it is only about a code style.
Further reading:
Your basic toolkit:
return
statement with zero values to match the function return type. It helps save a few keystrokes. However, be careful using it, the project seems to be not in active development for a long while.gofmt
with more rules. It is fully compatible with gofmt
and helpful.For historical reasons, Go extension for VSCode support specifying only one code formatter at once. So, every next level tool calls all previous tools under the hood:
goimports
calls gofmt
.goreturns
calls goimports
.gofumpt
provides gofumports
which is goimports
calling gofumpt
instead of gofmt
.So, I use gofumports
as my code formatter in VSCode, which includes gofmt
, gofumpt
, and goimports
.
A few smaller code formatters that can come in handy:
T{1, 2, 3}
) into keyed ones (T{A: 1, B: 2, C: 3}
). This description says everything. Always use keyed struct literals because the order is hard to remember, can be changed, and so on.See awesome-go-code-formatters for more tools.
If you have a custom rule you’d like to validate or reformat in your project, there are a few linters and tools that can be helpful:
Frameworks for pre-commit hooks: