Go to language warnings and errors

It seems that the GO language does not contain warnings. I have observed several instances. 1. "declared and not used" (if the variable is declared and not used everywhere it gives an error and does not compile the program) 2. "imported and not used" (similarly, if the package is imported, but not used wherever it gives an error and does not compile the program) Can someone help. If they have pointers.

+8
go
source share
3 answers

Go is trying to prevent this situation:

The boy smokes and leaves smoke rings in the air. The girl gets annoyed with smoke and tells her lover: "Can't you see the warning written on the cigarette packet, smoking is bad for your health!"

The boy replies: "Honey, I am a programmer. We do not worry about warnings, we only worry about errors."

Basically, Go just won't let you go with unused variables and unused imports and other things that are usually a warning in other languages. It helps you do a good job.

+13
source share

Go Programming Language Help

Can I stop these complaints about my unused variable / import?

The presence of an unused variable may indicate an error, while an unused import simply slows down the compilation. Accumulate enough unused imports in your code tree, and everything can become very slow. For these reasons, Go does not allow it.

When developing code, it usually creates such situations temporarily, and it may be annoying that you need to edit them before the program compiles.

Some have asked the compiler option to disable these checks or to a lesser extent reduce them to warnings. Such an option has not been added, though, since the compiler options should not affect the semantics of the language and because the Go compiler does not report warnings, only errors that prevent compilation.

There are two reasons for the lack of warnings. Firstly, if itโ€™s worth complaining about it, itโ€™s worth fixing the code. (And if this is not worth fixing, it is not worth mentioning.) Secondly, the presence of a compiler to generate warnings encourages the implementation to warn of weak cases that can make the compilation noisy, masking real errors that should be fixed.

However, itโ€™s easy to handle the situation. Use an empty identifier so that unused things are preserved during development.
import "unused" // This declaration marks the import as used by referencing an // item from the package. var _ = unused.Item // TODO: Delete before committing! func main() { debugData := debug.Profile() _ = debugData // Used only during debugging. .... } 
+13
source share

One solution for unused imports is to use goimports, which is the gofmt fork. It automatically adds missing imports and removes unused ones (in addition to formatting your code).

http://godoc.org/code.google.com/p/go.tools/cmd/goimports

I set up my editor to automatically run goimports whenever I save my code. I canโ€™t imagine how to write code without it now.

+1
source share

All Articles