在if..else语句中未声明变量

LiJ*_*ung 15 global-variables go

我刚刚开始学习go lang,我很担心在go lang中声明变量

例如我已经宣布req,erif ... else语句内.

if strings.EqualFold(r.Method, "GET") || strings.EqualFold(r.Method, "") {
    req, er := http.NewRequest(r.Method, r.Uri, b)
} else {
    req, er := http.NewRequest(r.Method, r.Uri, b)
}


if er != nil {
    // we couldn't parse the URL.
    return nil, &Error{Err: er}
}

// add headers to the request
req.Host = r.Host
req.Header.Add("User-Agent", r.UserAgent)
req.Header.Add("Content-Type", r.ContentType)
req.Header.Add("Accept", r.Accept)
if r.headers != nil {
    for _, header := range r.headers {
        req.Header.Add(header.name, header.value)
    }
}
Run Code Online (Sandbox Code Playgroud)

但我从终端得到了错误

./goreq.go:127: req declared and not used
./goreq.go:127: er declared and not used
./goreq.go:129: req declared and not used
./goreq.go:129: er declared and not used
Run Code Online (Sandbox Code Playgroud)

看起来像我在里面声明的任何东西如果声明不起作用......我怎么能解决它?

Arj*_*jan 28

因为变量仅在声明它们的范围内定义:

package main

import "fmt"

func main() {
    a := 1
    fmt.Println(a)
    {
        a := 2
        fmt.Println(a)
    }
    fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)

去玩

=和之间的区别:=仅在于=赋值,:=是变量声明和赋值的语法

这个:

a := 1
Run Code Online (Sandbox Code Playgroud)

相当于:

var a int
a = 1
Run Code Online (Sandbox Code Playgroud)

你可能想要的是:

var req *http.Request
var er error
if strings.EqualFold(r.Method, "GET") || strings.EqualFold(r.Method, "") {
    req, er = http.NewRequest(r.Method, r.Uri, b)
} else {
    req, er = http.NewRequest(r.Method, r.Uri, b)
}


if er != nil {
    // we couldn't parse the URL.
    return nil, &Error{Err: er}
}

// add headers to the request
req.Host = r.Host
req.Header.Add("User-Agent", r.UserAgent)
req.Header.Add("Content-Type", r.ContentType)
req.Header.Add("Accept", r.Accept)
if r.headers != nil {
    for _, header := range r.headers {
        req.Header.Add(header.name, header.value)
    }
}
Run Code Online (Sandbox Code Playgroud)