douba4275 2017-01-10 16:49
浏览 123

Golang::=左侧没有新变量,而类似的错误未发生

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
", 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
", 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
", err)
            os.Exit(1)
        }
        b, err := ioutil.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil {
            fmt.Fprintf(os.Stderr, "fetch: reading %s: %v
", url, err)
            os.Exit(1)
        }
        fmt.Printf("%s", b)
    }
}

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

  • 写回答

2条回答 默认 最新

  • duanpo2813 2017-01-10 16:51
    关注

    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)

    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line