VSCode supports automatically formatting code when saving, which is very helpful for maintaining clean and consistent code while writing Go. To configure VSCode to automatically format Go code on save, follow these steps:
-
Install the Go Language Extension First, ensure you have installed the official Go extension from the VSCode Extensions Marketplace. Search for 'Go' and install it.
-
Configure
settings.jsonNext, configure the VSCodesettings.jsonfile to enable automatic formatting on save. You can access this file in two ways:- Use the shortcut
Ctrl + ,to open settings, then click the{}icon in the top-right corner to enter thesettings.jsoneditor. - Or navigate to
File > Preferences > Settingsvia the menu bar, then click the{}icon in the top-right corner.
In the
settings.jsonfile, add or verify that the following settings are included:json"[go]": { "editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": true } }, "go.formatTool": "gofmt" // You can use other formatters like "goimports" or "goreturns" as neededThese settings enable:
- Automatic formatting of Go files when saving.
- Automatic organization of imports when saving.
- Setting
gofmtas the default formatter; replace it withgoimportsorgoreturnsas needed.
- Use the shortcut
-
Install Necessary Tools If this is your first configuration, the VSCode Go extension may prompt you to install necessary Go tools, including formatters like
gofmtorgoimports. Follow the prompts to install these tools. Typically, just click the install button in the pop-up notification. -
Test the Configuration After setting up, try editing a Go file and saving it. VSCode should automatically format the code. If formatting does not occur, verify that all tools are correctly installed and the
settings.jsonconfiguration is accurate.
Here's an example: Suppose I'm writing a Go program and I want the code to be automatically formatted and unused imports to be removed upon saving the file. I installed the Go extension and configured settings.json as per the above steps. Then, I wrote some unformatted code and intentionally retained some unused imports. When I saved the file, VSCode automatically formatted the code, removing extra whitespace and indentation, and deleting unused imports. This automated process significantly enhances development efficiency and maintains code cleanliness.