Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid annoying error "declared and not used"

Tags:

go

I'm learning Go but I feel it is a bit annoying that when compiling, I should not leave any variable or package unused.

This is really quite slowing me down. For example, I just wanted to declare a new package and plan to use it later or just uncomment some command to test. I always get the error and need to go comment all of those uses.

Is there any way to avoid this kind of check in Go?

like image 262
A-letubby Avatar asked Feb 13 '14 02:02

A-letubby


People also ask

Is declared but not used Golang?

It means that you have declared a variable in the code but did not used it anywhere. This makes the code crash because go wants you to write clean code which is easy to understand and use every variable you declare.


1 Answers

That error is here to force you to write better code, and be sure to use everything you declare or import. It makes it easier to read code written by other people (you are always sure that all declared variables will be used), and avoid some possible dead code.

But, if you really want to skip this error, you can use the blank identifier (_) :

package main  import (     "fmt" // imported and not used: "fmt" )  func main() {     i := 1 // i declared and not used } 

becomes

package main  import (     _ "fmt" // no more error )  func main() {     i := 1 // no more error     _ = i } 

As said by kostix in the comments below, you can find the official position of the Go team in the FAQ:

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation. Accumulate enough unused imports in your code tree and things can get very slow. For these reasons, Go allows neither.

like image 146
Florent Bayle Avatar answered Sep 30 '22 15:09

Florent Bayle