I'm using GoLand IDE to code in Go. When I save a file, I'd like that the unused imports disappear (like VS code)
I have enable "Optimize imports" in "Code" -> "Show reformat file dialog". But when I save the file, imports it's still present
goimports If your project does not have goimports, click the go get goimports link in the Goimports file notification window. Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports: go get golang.org/x/tools/cmd/goimports . Press Enter .
If your version of GoLand 2021.2 or higher, you can enable Run gofmt on code reformat option under Preferences/Settings | Editor | Code Style | Go | Other (it is enabled by default). After that, execute Code | Reformat Code ( Option + Command + L on macOS) and gofmt will be executed after internal GoLand formatter.
Currently, GoLand offers three ways to interact with ‘go fmt’: dedicated actions, before commit tools, and file watchers. Under the Tools | Go Tools menu, you can find two actions related to code formatting: Go Fmt File and Go Fmt Project.
When you use this grouping, GoLand puts all imports that begin with the specified string after third-party packages. Open settings by pressing Ctrl+Alt+S and navigate to Editor | Code Style | Go. Click the Imports tab. From the Sorting type list, select goimports.
Otherwise, open the Terminal tool window (View | Tool Windows | Terminal), and type the following command to install goimports: go get golang.org/x/tools/cmd/goimports. Press Enter. To add missing imports, navigate to Tools | Go Tools and click Goimports file. The goimports tool also formats your code in the same style as gofmt.
If you’ve never used GoLand before, you may be surprised that there is more than one internal reason to modify file content. Indeed, conventional text editors typically have a straightforward workflow. You open a file and modify it, and then you either explicitly save it or close the editor, losing your changes.
Two separate entries were added to the File Watchers that are enabled by default. One for formatting the code on save, one for optimising the imports on save:
How the imports are sorted, grouped, etc. can be further defined in the Code Style settings for Go:
There is another small option to run gofmt
on reformat in the Other
tab of Go's Code Style settings:
The setting to set up gofmt
or goimports
on save is in the File Watchers. Here you can add a new file watcher at the bottom and select gofmt
or goimports
from the list.
Setting this to goimports
will do both:
gofmt
)"On Save" tab was removed in GogLand EAP 16.
In newer versions you have to go to Settings
-> Tools
-> File Watchers
and add goimports
there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With