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

Format on Save in Go with VS Code [2023]

By Lane Wagner on May 26, 2023

Curated backend podcasts, videos and articles. All free.

Want to improve your backend development skills? Subscribe to get a copy of The Boot.dev Beat in your inbox each month. It's a newsletter packed with the best content for new backend devs.

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.

Find a problem with this article?

Report an issue on GitHub