狐狸.fox 2014-02-13 02:09 采纳率: 0%
浏览 279
已采纳

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

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

  • 写回答

5条回答 默认 最新

  • from.. 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条)

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名