变量定义未定义

huangapple go评论78阅读模式
英文:

Variable definition is not defined

问题

我已经搜索了Google并看到了一些示例,但是还是不太明白。我刚开始学习Go语言,所以希望有人能为我解释一下。我有以下的代码:

var configFile string
var keyLength int
var outKey string
var outconfig string

for index, item := range args {

	if strings.ToLower(item) == "-config" {
		configFile = args[index + 1]
	}else if strings.ToLower(item) == "-keylength" {
		keyLength, _ = strconv.Atoi(args[index + 1])
	}else if strings.ToLower(item) == "-outkey" {
		outKey = args[index + 1]
	}else if strings.ToLower(item) == "-outconfig" {
		outconfig = args[index + 1]
	}        
}	

但是在定义所有变量的地方,我得到了一个错误,错误信息是"configFile declared but not used"。如果我能得到一些建议,帮助我更好地理解这个问题。

英文:

I've searched Google and saw some samples, but it's just not clicking. I'm new to Go, so I hope someone can clarify this for me. I have the following code:

var configFile string
var keyLength int
var outKey string
var outconfig string

for index, item := range args {

	if strings.ToLower(item) == "-config" {
		configFile = args[index + 1]
	}else if strings.ToLower(item) == "-keylength" {
		keyLength, _ = strconv.Atoi(args[index + 1])
	}else if strings.ToLower(item) == "-outkey" {
		outKey = args[index + 1]
	}else if strings.ToLower(item) == "-outconfig" {
		outconfig = args[index + 1]
	}        
}	

But I'm getting an error for all the variables where it's being defined with the following error "configFile declared but not used". If I can get some advice to help me better understand this problem

答案1

得分: 0

你给变量赋值,但之后从未使用过它们。这就是为什么 Go 抛出错误。

看看这个例子:

package main

func f() {
	var unassignedVar string
	var unusedVar = "I am not read"
	var usedVar = "I am read"

	print(usedVar)
}

对于前两个变量,Go 会抛出错误:unassignedVar 甚至没有被赋值,unusedVar 被赋了一个值但之后没有使用。usedVar 被赋了一个值并在后面使用了。

在 Go Playground 上查看示例:https://go.dev/play/p/72lRGyxDn4Y

英文:

You assign values to the variables, but never use them after. That's why Go throws an error.

See this example:

package main

func f() {
	var unassignedVar string
	var unusedVar = "I am not read"
	var usedVar = "I am read"

	print(usedVar)
}

For the first two variables, Go will throw an error: unassignedVar is not even assigned a value, unusedVar is assigned a value but not used afterwards. usedVar is both assigned a value and used later on.

See the example on the Go Playground.

huangapple
  • 本文由 发表于 2022年11月17日 15:54:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/74471907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定