douxing5598 2014-02-13 02:09
浏览 33
已采纳

如何避免“声明且未使用”的烦人错误

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?

  • 写回答

5条回答 默认 最新

  • douhuai2861 2014-02-13 02:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数