go - 如何修复这个简单程序中的 'declared but not used' 编译器错误?

标签 go declaration

我正在努力学习围棋。我真的不明白为什么编译器说我没有使用变量。在我看来,我正在使用该变量作为 Println 的参数。

我的教科书说:

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)))
}

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/

相关文章:

Go:如何找出 rune 的 Unicode 属性?

const 导致 "formal parameter different from declaration"警告

javascript - Javascript 中不明确的函数声明

c++ - 数组的 Stackoverflow 数组

java - 我应该在哪里声明此代码中的字段才能编译?

go - 使用嵌入式 core.v1.PodSpec 验证 CRD

go - 从交叉编译的二进制文件构建RPM软件包Go app tarball

ssl - Golang 中的 TLS 连接问题

arrays - 在 Go 中克隆 float slice 而不影响原始

c - 如何在 C 中使用 extern?