如何避免恼人的错误“声明而不使用" [英] How to avoid annoying error "declared and not used"

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

问题描述

我正在学习 Go,但我觉得编译时不应该留下任何未使用的变量或包,这有点烦人.

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.

有什么办法可以在 Go 中避免这种检查吗?

Is there any way to avoid this kind of check in Go?

推荐答案

这里的错误迫使您编写更好的代码,并确保使用您声明或导入的所有内容.它可以更轻松地阅读其他人编写的代码(您始终确保将使用所有声明的变量),并避免一些可能的死代码.

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
}

变成

package main

import (
    _ "fmt" // no more error
)

func main() {
    i := 1 // no more error
    _ = i
}

正如kostix在下面的评论中所说的,你可以在FAQ中找到Go团队的官方立场:

As said by kostix in the comments below, you can find the official position of the Go team in the FAQ:

未使用的变量的存在可能表示存在错误,而未使用的导入只会减慢编译速度.在你的代码树中积累足够多的未使用的导入,事情会变得非常缓慢.由于这些原因,Go 不允许.

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.

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

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