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?