Variable not declared, inside a if..else statement

前端 未结 2 1635
情歌与酒
情歌与酒 2021-01-04 00:53

I\'m just started learning go lang, and I am confused about declaring variables in go lang

for example I\'ve declare req, er inside if...el

相关标签:
2条回答
  • 2021-01-04 01:40

    Because variables are only defined in the scope in which they are declared:

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

    go play

    The difference between = and := is that = is just assignment and := is syntax for variable declaration and assigment

    This:

    a := 1
    

    is equivalent to:

    var a int
    a = 1
    

    What you probably want is:

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-04 01:44

    This is because you have declared the variables req and er inside the if else condition and are trying to use it outside the scope (the scope is just the if and else inside which they are declared).

    You need to declare er and req outside the if else

    0 讨论(0)
提交回复
热议问题