Golang:在 := 的左侧没有新的变量,而类似的情况没有出现这个错误。

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

Golang: no new variables on left side of :=, while a similar one didn't occur this error

问题

我已经写了一些代码,根据《Go程序设计语言》这本书的指导,打印出在URL上找到的内容。编译器对以下代码进行了投诉,指出**在 := 的左侧没有新变量**。

package main

import (
    "fmt"
    "net/http"
    "os"
    "io"
)

func main() {
    for _, url := range os.Args[1:] {
        resp, err := http.Get(url)
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
            os.Exit(1)
        }
        _, err := io.Copy(os.Stdout, resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
            os.Exit(1)
        }
    }
}

我已经知道这是由于重新声明某些变量导致的。而以下代码通过了编译。

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

func main() {
    for _, url := range os.Args[1:] {
        resp, err := http.Get(url)
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
            os.Exit(1)
        }
        b, err := ioutil.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
            os.Exit(1)
        }
        fmt.Printf("%s", b)
    }
}

它没有重新声明变量err吗?那么它是如何通过编译的呢?

英文:

I have written some code to prints the content found at a URL following the guide of a book named The Go Programming Language. The compiler complained about the following code that no new variables on left side of :=.

package main

import (
    "fmt"
    "net/http"
    "os"
    "io"
)

func main() {
    for _, url := range os.Args[1:] {
        resp, err := http.Get(url)
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
            os.Exit(1)
        }
        _, err := io.Copy(os.Stdout, resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
            os.Exit(1)
        }
    }
}

And I have known that this was caused by re-declaration of certain variables. While the following one passed the compilation.

package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

func main() {
    for _, url := range os.Args[1:] {
        resp, err := http.Get(url)
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: %v\n", err)
            os.Exit(1)
        }
        b, err := ioutil.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v\n", url, err)
            os.Exit(1)
        }
        fmt.Printf("%s", b)
    }
}

Didn't it re-declare the variable err? Then how could it pass the compilation?

答案1

得分: 13

如果在赋值语句中有任何新的变量(例如 b),那么 := 将创建它。如果所有变量都不是新的,那么你会得到你正在遇到的错误。_ 不是一个新的变量。

由于你已经有了所有现有的变量,你可以在你的 io 行中直接使用 =

_, err = io.Copy(os.Stdout, resp.Body)

当你使用 b 而不是 _ 时,:= 声明了 b,但将 err 视为标准赋值(即,就像使用了 = 一样)。

英文:

If there are any new variables in the assignment (e.g. b) then := will create it. If all variables are not new then you get the error you're getting. _ is not a new variable.

Since you have all existing variables you can just use = for your io line:

_, err = io.Copy(os.Stdout, resp.Body)

When you used b instead of _ then := declared b but treated err like a standard assignment (i.e. just as if a = was used)

答案2

得分: 4

它没有

只要左侧至少有一个新变量,并且其他变量已在同一代码块中以相同类型声明,你就可以使用:=。已经声明的变量只会改变它们的值。这基本上是为了方便。

具体描述可以参考这里:https://golang.org/ref/spec#Short_variable_declarations

英文:

It did not

You can use the := as long as there is at least one new variable at the left side and the other variables have already been declared in the same block with the same type. Already declared variables will just have their values changed. It's basically for convenience.

It is all described here : https://golang.org/ref/spec#Short_variable_declarations

huangapple
  • 本文由 发表于 2017年1月11日 00:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41574028.html
匿名

发表评论

匿名网友

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

确定