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

时间:2014-01-31 13:29:28

标签: go global-variables

我刚刚开始学习go lang,我对go lang中声明变量感到困惑

例如我在if ... else语句中声明reqer

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)
    }
}

但我从终端

收到错误
./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

似乎我在里面声明的任何内容如果语句不起作用......我怎么能解决它?

2 个答案:

答案 0 :(得分:21)

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

package main

import "fmt"

func main() {
    a := 1
    fmt.Println(a)
    {
        a := 2
        fmt.Println(a)
    }
    fmt.Println(a)
}

go play

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

此:

a := 1

相当于:

var a int
a = 1

你可能想要的是:

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)
    }
}

答案 1 :(得分:1)

这是因为您已在req条件中声明了变量erif else,并尝试在范围之外使用它(范围只是ifelse在其中宣布它们。)

您需要在er

之外声明reqif else