为什么golang编译器认为变量已声明但未被使用? [英] Why does golang compiler think the variable is declared but not used?

查看:711
本文介绍了为什么golang编译器认为变量已声明但未被使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

reader:= io.MultiReader(读者...)
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)
}



编译错误是声明和未使用。但我认为我已经使用err来陈述。为什么编译器输出这个错误? c> err 在for之外,并且它没有被使用(for中的那个)。发生这种情况是因为您使用的是短变量声明(使用:= 运算符),它声明了一个新的 err 变量会影响在for外部声明的人。


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?

解决方案

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.

这篇关于为什么golang编译器认为变量已声明但未被使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆