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

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

问题描述

我正在学习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在以下评论中所述,您可以在常见问题解答中找到围棋团队的正式职位 :

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天全站免登陆