英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论