乐闻世界logo
搜索文章和话题

How to set vscode format golang code on save?

1个答案

1

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:

  1. 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.

  2. Configure settings.json Next, configure the VSCode settings.json file 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 the settings.json editor.
    • Or navigate to File > Preferences > Settings via the menu bar, then click the {} icon in the top-right corner.

    In the settings.json file, 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 needed

    These settings enable:

    • Automatic formatting of Go files when saving.
    • Automatic organization of imports when saving.
    • Setting gofmt as the default formatter; replace it with goimports or goreturns as needed.
  3. Install Necessary Tools If this is your first configuration, the VSCode Go extension may prompt you to install necessary Go tools, including formatters like gofmt or goimports. Follow the prompts to install these tools. Typically, just click the install button in the pop-up notification.

  4. 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.json configuration 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.

2024年6月29日 12:07 回复

你的答案