一尘不染

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

go

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

例如我已经声明reqer里面if … 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)
    }
}

但是终端出现错误

./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

好像我在If语句中声明的任何内容都不起作用…我该如何解决?


阅读 394

收藏
2020-07-02

共1个答案

一尘不染

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

package main

import "fmt"

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

去玩

之间的区别=,并:==仅仅是分配和:=对变量的声明和分配新建分配FY语法

这个:

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)
    }
}
2020-07-02