Go has hard opinions about how you should style and format your code. Setting up your VS Code environment to enforce the standard linting and formatting rules can save you a ton of time.
I don’t like to think about code styling. I like to type a bunch of code with incorrect spacing and press (ctrl+s)
or (cmd+s)
to save my code and auto-format it.
What you’ll need ๐
- Make sure you have the latest version of Go installed on your machine (as of the time of writing, 1.20)
- Install the Official Golang VS Code Plugin
Next, open your settings.json file in VS Code. These settings can be specific to a single workspace or to your user account, whichever you prefer.
I use the following settings:
{
// format all files on save if a formatter is available
"editor.formatOnSave": true,
// I use "goimports" instead of "gofmt"
// because it does the same thing but also formats imports
"go.formatTool": "goimports",
// go-specific settings
"[go]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"[go.mod]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}
Why goimports
and not gofmt
? ๐
Simply put, goimports does everything gofmt
does but additionally formats import statements. I like that.
Bonus: Auto-Update, Staticcheck and Vetting ๐
I also have these additional settings to add even more functionality to my VS Code environment. If you find them useful, feel free to use them.
{
"go.toolsManagement.autoUpdate": true,
"go.vetOnSave": "package"
}
The staticcheck tools should automatically work within VS Code if you’re using the language server and the Go extension and have it installed.
Not Working? ๐
If it still isn’t working, you likely need to reload your VS Code window and/or install the missing tools that VS Code is prompting you to install via popups in the bottom-right of the editor.
I will do my best to keep this guide up to date. Let me know if it isn’t working for you in the boot.dev Discord.
PS: If you’d like to learn Go, you can check out my full Go course here.