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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效