Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop GoLand from auto removal of unused imports?

Tags:

go

goland

I am working with JetBrains GoLand and wondering if it's possible to somehow disable the auto removal of unused imports. I have searched the JetBrains forums earlier and there is no such information specifically for Goland.

This picture shows the problem.

like image 968
nombreinvicto Avatar asked Jul 18 '18 21:07

nombreinvicto


People also ask

Why should we remove unused imports?

An unused import still creates a dependency. If you don't realize that a dependency is only because of unused imports, you can waste time updating the module version, investigating vulnerability reports related to that module, etc.

How do I Auto Import classes in Intellij?

In the Settings/Preferences dialog ( Ctrl+Alt+S ), click Editor | General | Auto Import. Make sure the necessary options are selected for the Show auto-import tooltip for setting (both checkboxes, Classes and Static methods and fields, are enabled by default).

How do I get rid of unused imports in Intellij?

CTRL + ALT + O ---> to remove the unused imports in windows. However, you can also change the keymap of "Optimize Imports" in settings.


3 Answers

Another solution is to name your import as "_". For example: import _ "your/package". Doing this will prevent auto removal.

like image 129
Junbang Huang Avatar answered Oct 18 '22 17:10

Junbang Huang


This feature is used so that you do not receive compilation errors for unused imports from Go. You can deactivate the feature via:

Settings (Preferences) > Go > Imports > Optimize imports on the fly

However my recommendation is to leave this as is and instead let the IDE manage the imports for you.

For example, you can start typing template.New inside the main function and the IDE will ask which "template" package to import as there are two packages in the standard library "text/template" and "html/template". When only one package is available, that will be imported automatically. When you will remove the last reference to the "template" package, the IDE will remove the import automatically, thus allowing you to run the code without any compilation issues.

like image 20
dlsniper Avatar answered Oct 18 '22 19:10

dlsniper


The behavior was slightly changed in the 2021.2 version of GoLand and higher (GO-11362).

Previous behavior (2021.1.3 and lower):

enter image description here

Current one (2021.2 and higher):

enter image description here

So, it was slightly updated and there is no reason to disable Optimize imports on the fly, but as dlsniper said you can start typing your code and import packages later. It is a bit convenient way.

like image 5
s0xzwasd Avatar answered Oct 18 '22 19:10

s0xzwasd