douchaqi3369 2016-06-07 20:41
浏览 11
已采纳

赋值且未在if语句中使用的值

I wrote an example of the problem I'm seeing in go playground: https://play.golang.org/p/rPCqAC56Ff

It's pretty self evident, but I'm declaring a variable outside of an if statement, setting variable in if and then using outside of if.

The question is simple, why doesn't this work?

package main

import (
    "fmt"
    "os"
)

func main() {
    var foo string
    if true {
        foo = "foo"
    } else {
        foo, found := os.LookupEnv("GOPATH")
        if !found {
            fmt.Printf("who cares.
")
        }
    }
    println(foo)
}
  • 写回答

2条回答 默认 最新

  • douzuizhuo0587 2016-06-07 22:05
    关注

    From Go documentation:

    An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.

    := in the else block redeclares foo, so that foo now refers to a whole new variable with the same name, a variable which is never used. Even if we somehow reached the else block, the println(foo) at last line wouldn't print our $GOPATH as that's stored to the other foo variable (or was until the whole variable went out of scope)

    Correct code would be:

    func main() {
        var foo string
        if true {
            foo = "foo"
        } else {
            var found bool
            foo, found = os.LookupEnv("GOPATH")
            if !found {
                fmt.Printf("who cares.
    ")
            }
        }
        println(foo)
    }
    

    It's easy to get confused since this code works fine even though foo is redeclared before it used:

    func main() {
        var foo string
        foo = "foo"
        foo, found := os.LookupEnv("GOPATH")
        if !found {
            fmt.Printf("who cares.
    ")
        }
        println(foo)
    }
    

    What's happening here is that there's also another, different kind of legal redeclaration in Go:

    Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.

    So in this other kind of redeclaration, no new foo variable is actually created and it works just like assignment to foo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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