如何修复这个简单程序中的“声明但未使用”编译器错误?

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

How to fix 'declared but not used' compiler error in this simple program?

问题

我正在尝试学习Go语言。我真的不明白为什么编译器说我没有使用一个变量。在我看来,我是将这个变量作为Println的参数使用了。

我的教材上写着:

> 在这个for循环中,i代表数组中的当前位置,valuex[i]相同。

package main

import "fmt"

func main() {
	
	x := [5]float64{ 1,2,3,4,5 }
	i := 0
	var total float64 = 0

	for i, value := range x {
		total += value
		fmt.Println(i, value)
	}	
	fmt.Println("Average:", total / float64(len(x)))
}

在OS X上的输出结果为:

go run main.go 
# command-line-arguments
./main.go:8: i declared and not used

当然,fmt.Println(i, value)这一行代码是在使用变量i的。

英文:

I am trying to learn Go. I really don't understand why the compiler is saying that I am not using a variable. It seems to me that I am using the variable as an argument to Println.

My textbook states:

> In this for loop i represents the current position in the array and
> value is the same as x[i]

package main

import "fmt"

func main() {
	
	x := [5]float64{ 1,2,3,4,5 }
	i := 0
	var total float64 = 0

	for i, value := range x {
		total += value
		fmt.Println(i, value)
	}	
	fmt.Println("Average:", total / float64(len(x)))
}

Output on OS X:

go run main.go 
# command-line-arguments
./main.go:8: i declared and not used

Surely this fmt.Println(i, value) is using the variable i?

答案1

得分: 2

如何修复编译器的错误信息?

从你的程序中删除外部的 i

package main

import "fmt"

func main() {

    x := [5]float64{1, 2, 3, 4, 5}
    var total float64 = 0

    for i, value := range x {
        total += value
        fmt.Println(i, value)
    }
    fmt.Println("Average:", total/float64(len(x)))
}

确保 fmt.Println(i, value) 使用的是 for 循环内部定义的变量 i(注意 :=),如下所示:

for i, value := range x
    ^        ^

外部的变量 i 没有被使用。

英文:

> How to fix the compiler message?

Remove the outer i from your program:

package main

import "fmt"

func main() {

	x := [5]float64{1, 2, 3, 4, 5}
	var total float64 = 0

	for i, value := range x {
		total += value
		fmt.Println(i, value)
	}
	fmt.Println("Average:", total/float64(len(x)))
}

> Surely this fmt.Println(i, value) is using the variable i?

Yes, but the one you're defining inside the for loop. (note the :=), here:

for i, value := range x
    ^        ^

The outer variable i is never used.

huangapple
  • 本文由 发表于 2014年11月24日 00:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/27091248.html
匿名

发表评论

匿名网友

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

确定