How can I get rid of the unused import error in Go?
Go treats unused imports as errors. For example, if I comment or delete the last line that’s using an imported function from a package, Go complains and forces me to delete the import from package declaration as well.
I find this very annoying especially during debugging when I want to temporarily remove a line and re-introduce it back later. Is there a way to disable this behavior?
package main
import (
"fmt"
"strconv"
)
func main() {
var i int
//i, _ = strconv.Atoi("-42") >> ERROR: imported and not used: "strconv"
fmt.Println(i)
}
Accepted Answer
Using blank identifier _
to refer to a symbol from the imported package
It is not a good idea to leave unused imports in your program. It not only bloats your code but also slows compilation down. However, during active development or troubleshooting, this need often arrises and it certainly is annoying to remove the package from imports only to re-introduce it again. You can use the blank identifier _
to get around this. Just assign any symbol from the imported package to the blank identifier and that will do the trick.
package main
import (
"fmt"
"strconv"
)
var _ = strconv.Atoi // todo remove later: silencing unused import error for debugging.
func main() {
var i int
i, _ = strconv.Atoi("-42")
fmt.Println(i)
}
Things to note:
- Global declarations to silence unused import errors should come right after the imports
- Add a comment declaring their intent to make it easy for other
- Do this only when your program is under active development; remove unused imports before going to production
Importing for side-effects
You can also import a package for its side-effects using blank identifier and not use any of it exported functions explicitly. For example, you could do the following the the program will run just fine even though the strconv
package is not used.
package main
import (
"fmt"
_ "strconv"
)
func main() {
var i int
fmt.Println(i)
}
However, importing for side-effects is not a good strategy for silencing unused errors. Unlike the previous approach, it doesn’t signify work in progress (there are times when you want to do this to initialize something for side-effects i.e. import _ "net/http/pprof"
) and you must remove the blank identifier _
from the import if you want to use the package again. If you are going to go through all that trouble, you might comment and then uncomment the line itself. So, the var _ = ...
approach is preffered.