如何避免恼人的错误“声明和未使用”来自Golang [英] How to avoid annoying error "declared and not used" from Golang

查看:409
本文介绍了如何避免恼人的错误“声明和未使用”来自Golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Golang,但是我觉得在编译时,我不应该让任何变量或包未被使用。



这实在让我放慢了脚步。例如,我只是想声明一个新的包,并计划稍后使用它,或者只是取消注释某些要测试的命令。我总是得到错误,需要评论所有这些用途。



有没有办法在Golang中避免这种检查?

解决方案

这个错误是为了强制你编写更好的代码,并确保使用你声明或导入的所有东西。它使得阅读其他人编写的代码变得更加容易(你总是确信将使用所有声明的变量),并避免一些可能的死代码。



但是,如果你真的想跳过这个错误,你可以使用空白标识符(<$ c $

$ p $ package main

import(

$) $ bfmt//导入并未使用:fmt


func main(){
i:= 1 //我声明并未使用
}

变成

 包主要

导入(
_fmt//没有更多错误


func main(){
i:= 1 //不再有错误
_ = i
}

正如下面评论中的kostix所说,您可以在常见问题中找到Go团队的官方职位 存在未使用的变量可能指示错误,而未使用的导入只会减慢编译的速度。在您的代码树中积累足够多的未使用的导入,事情会变得非常缓慢。由于这些原因,Go不允许。


I'm learning Golang 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 Golang?

解决方案

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 wiil 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."

这篇关于如何避免恼人的错误“声明和未使用”来自Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆