Format on Save in Go with VS Code [2023]

Boot.dev Blog ยป Golang ยป Format on Save in Go With vs Code [2023]
Lane Wagner
Lane Wagner

Last published May 26, 2023

Subscribe to curated backend podcasts, videos and articles. All free.

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 ๐Ÿ”—

official golang vs code extension

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.

Find a problem with this article?

Report an issue on GitHub