Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Golang unused import error

Tags:

go

By default, Go treats unused import as error, forcing you to delete the import. I want to know if there exists some hope to change to this behavior, e.g. reducing it to warning.

I find this problem extremely annoying, preventing me from enjoying coding in Go.

For example, I was testing some code, disabling a segment/function. Some functions from a lib is no longer used (e.g. fmt, errors, whatever), but I will need to re-enable the function after a little testing. Now the program won't compile unless I remove those imports, and a few minutes later I need to re-import the lib.

I was doing this process again and again when developing a GAE program.

like image 480
Nick Avatar asked Oct 24 '13 08:10

Nick


3 Answers

Adding an underscore (_) before a package name will ignore the unused import error.

Here is an example of how you could use it:

import (
    "log"
    "database/sql"

    _ "github.com/go-sql-driver/mysql"
)

To import a package solely for its side-effects (initialization), use the blank identifier as explicit package name.

View more at https://golang.org/ref/spec#Import_declarations

like image 70
Ari Seyhun Avatar answered Nov 02 '22 17:11

Ari Seyhun


The var _ = fmt.Printf trick is helpful here.

like image 30
Volker Avatar answered Nov 02 '22 16:11

Volker


I have the same problem. I understand the reasoning for why they implemented the language to disallow unused imports and variables, but I personally find this feature annoying when writing my code. To get around this, I changed around my compiler to allow optional flags for allowing unused variables and imports in my code.

If you are interested, you can see this at https://github.com/dtnewman/modified_golang_compiler.

Now, I can simply run code with a command such as go run -gcflags '-unused_pkgs' test.go and it will not throw these "unused import" errors. If I leave out these flags, then it returns to the default of not allowing unused imports.

Doing this only required a few simple changes. Go purists will probably not be happy with these changes since there is good reason to not allow unused variables/imports, but I personally agree with you that this issue makes it much less enjoyable to code in Go which is why I made these changes to my compiler.

like image 26
dtzvi Avatar answered Nov 02 '22 16:11

dtzvi