doufei9946 2015-08-03 16:26
浏览 32
已采纳

有没有办法标记编译器忽略未使用的导入? [重复]

This question already has an answer here:

If the compiler can recognize that an import is unused, then is it possible to set it to continue with compilation without that import ?

Even if it's not possible, what are the pros/cons of such an option ?

</div>
  • 写回答

1条回答 默认 最新

  • duanji9264 2015-08-03 16:28
    关注

    No. For reasoning see the following FAQ:

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

    The presence of an unused variable may indicate a bug, while unused imports just slow down compilation, an effect that can become substantial as a program accumulates code and programmers over time. For these reasons, Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity.

    Still, when developing code, it's common to create these situations temporarily and it can be annoying to have to edit them out before the program will compile.

    Some have asked for a compiler option to turn those checks off or at least reduce them to warnings. Such an option has not been added, though, because 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 having no warnings. First, if it's worth complaining about, it's worth fixing in the code. (And if it's not worth fixing, it's not worth mentioning.) Second, having the compiler generate warnings encourages the implementation to warn about weak cases that can make compilation noisy, masking real errors that should be fixed.

    It's easy to address the situation, though. Use the blank identifier to let unused things persist while you're developing.

    What you may do is use the blank identifier when temporarily want to exclude something, e.g.

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

    Nowadays, most Go programmers use a tool, goimports, which automatically rewrites a Go source file to have the correct imports, eliminating the unused imports issue in practice. This program is easily connected to most editors to run automatically when a Go source file is written.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan