doumen1883 2014-01-31 13:29
浏览 80
已采纳

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

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...else statement.

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

But I've got error from terminal

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

seems like anything I declared inside If statement is not working... How can I solved it?

  • 写回答

2条回答 默认 最新

  • dongliyan9190 2014-01-31 13:36
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历