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?
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 (
_
) :becomes
As said by kostix in the comments below, you can find the official position of the Go team in the FAQ:
In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):
You can assign a useless/blank variable to the function so that it's no longer unused:
According to the FAQ:
I don't necessarily agree with this for various reasons not worth going into. It is what it is, and it's not likely to change in the near future.
For packages, there's the
goimports
tool which automatically adds missing packages and removes unused ones. For example:You should be able to run this from any half-way decent editor − for example for Vim:
The
goimports
page lists some commands for other editors, and you typically set it to be run automatically when you save the buffer to disk.Note that
goimports
will also rungofmt
.As was already mentioned, for variables the easiest way is to (temporarily) assign them to
_
:You can use a simple "null function" for this, for example:
Which you can use like so:
There's also a package for this so you don't have to define the
Use
function every time:One angle not so far mentioned is tool sets used for editing the code.
Using Visual Studio Code along with the Extension from lukehoban called
Go
will do some auto-magic for you. The Go extension automatically runsgofmt
,golint
etc, and removes and addsimport
entries. So at least that part is now automatic.I will admit its not 100% of the solution to the question, but however useful enough.