How to disable Golang unused import error

2019-01-17 01:59发布

问题:

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

I found this problem extremely annoying prevent 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.

回答1:

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



回答2:

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



回答3:

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.



回答4:

Use goimports. It's basically a fork of gofmt, written by Brad Fitzpatrick and now included in the go tools packages. You can configure your editor to run it whenever you save a file. You'll never have to worry about this problem again.



回答5:

If you are using the fmt package for general printing to console while you develop and test then you may find a better solution in the log package.



回答6:

Use if false { ... } to comment out some code. The code inside the braces must be syntactically correct, but can be nonsense code otherwise.



回答7:

put this on top of your document and forget about unused imports:

import (
    "bufio"
    "fmt"
    "os"
    "path/filepath"
)

var _, _, _, _ = fmt.Println, bufio.NewReader, os.Open, filepath.IsAbs


标签: go