英文:
How to fix 'declared but not used' compiler error in this simple program?
问题
我正在尝试学习Go语言。我真的不明白为什么编译器说我没有使用一个变量。在我看来,我是将这个变量作为Println
的参数使用了。
我的教材上写着:
> 在这个for循环中,i
代表数组中的当前位置,value
与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)))
}
在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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论