三生石@ 2014-02-13 02:09 采纳率: 100%
浏览 234
已采纳

如何避免恼人的错误"已声明和未使用"

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?

转载于:https://stackoverflow.com/questions/21743841/how-to-avoid-annoying-error-declared-and-not-used

  • 写回答

4条回答 默认 最新

  • 乱世@小熊 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.

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

报告相同问题?

悬赏问题

  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决