Some things in life you just have to experience to truly appreciate the value. One of these is auto-formatting/linting source code. When I started programming in Go in Vim, I naturally looked for editor support, and found the excellent vim-go project. Through this, I learned about gofmt and then goimports. These tools can be configured in your editor to automatically format your code when you save. goimports goes a step beyond and adds missing imports and removes unused ones.
Below are instructions on how to set up Visual Studio Code to auto-format code. Even though I use Neovim for most of my code editing, I still try out VS code and IntelliJ IDEA from time to time to learn what’s new in cutting-edge editors. I also recommend VS Code for most new Go developers — especially those coming from embedded systems development where an IDE is traditionally used. Give it a try — it will only take you a few minutes.
The instructions below should work with most systems (Windows, Linux, Mac). First, make sure Go and VS code are installed. Then install the Go VS code extension.
Next, type Ctrl-Shift-P to bring up the command palette and run Go: Install/Update Tools.
This will display a list of tools — select them all.
Next, configure VS Code to format on save. Open the settings by selecting File->Preferences->Settings from the menu. Select the “Format on Save” option and set the timeout to something larger than the default, like 5000ms.
Last, select goimports as the code formatting tool — this will automatically manage the imports in your file, as well as formatting the code.
Now, open a Go source file. Mess up the formatting of some code and then save — the code should be automatically formatted. Similarly, if you remove one of the import statements that is being used, and save, the imports will be corrected. Unused imports will be removed.
These tools allow you to focus on writing software and let the tools worry about formatting and imports. Prettier code with less effort — why not?