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

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

问题描述

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

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
", data[:n])
    }
    os.Exit(0)
}

编译错误是错误声明但未使用".但我想我在 for 语句中使用了 err.为什么编译器会输出这个错误?

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?

推荐答案

for 内的 err 遮蔽了 for 外的 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.

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

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