为什么 Golang 编译器会认为变量已声明但未使用?

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

Why does golang compiler think the variable is declared but not used?

问题

我是一个新手学习golang,我写了一个测试io包的程序:

func main() {
    readers := []io.Reader{
        strings.NewReader("from string reader"),
        bytes.NewBufferString("from bytes reader"),
    }

    reader := io.MultiReader(readers...)
    data := make([]byte, 1024)

    var err error

    for err != io.EOF {
        n, err := reader.Read(data)
        fmt.Printf("%s\n", data[:n])
    }
    os.Exit(0)
}

编译错误是"err declared and not used"。但是我认为我在for语句中使用了err。为什么编译器会输出这个错误?

英文:

I am a newbee to golang, and I write a program to test io package:

func main() {
    readers := []io.Reader{
	     strings.NewReader("from string reader"),
	     bytes.NewBufferString("from bytes reader"),
    }

    reader := io.MultiReader(readers...)
    data := make([]byte, 1024)

    var err error
    //var n int

    for err != io.EOF {
	    n, err := reader.Read(data)
	    fmt.Printf("%s\n", data[:n])
    }
    os.Exit(0)
}

The compile error is "err declared and not used". But I think I have used err in for statement. Why does the compiler outputs this error?

答案1

得分: 28

在for循环内部的err变量遮蔽了外部的err变量,并且没有被使用(for循环内部的那个)。这是因为你使用了短变量声明(使用:=运算符),它声明了一个新的err变量,遮蔽了在for循环外部声明的那个。

英文:

The err inside the for is shadowing the err outside the for, and it's not being used (the one inside the for). This happens because you are using the short variable declaration (with the := operator) which declares a new err variable that shadows the one declared outside the for.

huangapple
  • 本文由 发表于 2013年9月5日 10:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/18626933.html
匿名

发表评论

匿名网友

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

确定