我正在努力学习围棋。我真的不明白为什么编译器说我没有使用变量。在我看来,我正在使用该变量作为 Println
的参数。
我的教科书说:
In this for loop
i
represents the current position in the array andvalue
is the same asx[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
吗?
最佳答案
How to fix the compiler message?
从你的程序中移除外层的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)))
}
Surely this fmt.Println(i, value) is using the variable i?
是的,但是您在 for
循环中定义的那个。 (注意 :=
),这里:
for i, value := range x
^ ^
从未使用过外部变量i
。
关于go - 如何修复这个简单程序中的 'declared but not used' 编译器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091248/