Is there a way to mark the compiler to ignore unused imports?

If the compiler can recognize that the import is not in use, can it continue with compilation without import?

Even if this is not possible, what are the pros and cons of such an option?

+3


source to share


1 answer


Not. For the rationale, see the following frequently asked questions:

FREQUENTLY ASKED QUESTIONS: Can I stop these complaints about my unused variable / import?

The presence of an unused variable may indicate an error, while unused imports simply slow down compilation, which can become significant as the program accumulates code and programmers over time. For these reasons, Go refuses to compile programs with unused variables or imports, trading in short-term convenience for long-term build speed and program clarity.

However, when developing code, there is usually a situation where these are temporarily created and it can be frustrating that you need to edit them before compiling the program.

Some have asked the compiler option to disable these checks, or at least reduce them to warnings. However, this option was not added because 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. First, if it's worth complaining about, it's worth pinning the code. (And if it’s not worth fixing, it’s not worth mentioning.) Second, the presence of the compiler generates warnings, prompting the implementation to warn of weak cases that can make compilation noisy, masking real bugs that need to be fixed.

However, it is easy to deal with the situation. Use an empty identifier to keep things unused during development.


What you can do is use an empty identifier when you temporarily want to exclude something, eg.

import (
    "fmt"
    _ "time"  // This will make the compiler stop complaining
)

      

Most Go programmers nowadays use the goimports tool , which automatically overwrites the Go source file to have the correct imports, eliminating unused imports in practice. This program easily connects to most editors to automatically launch when a Go source file is written.

+10


source







All Articles