dongya2029 2018-08-23 05:07
浏览 32
已采纳

未定义的变量golang [重复]

This question already has an answer here:

Can someone tell me why num is undefined :: Here is go playground link also you can check this code here: https://play.golang.org/p/zR9tuVTJmx-

package main
import "fmt"
func main() {
    if 7%2 == 0 {
        num := "first"
    } else {
        num := "second"
    }
    fmt.Println(num)

  }
</div>
  • 写回答

1条回答 默认 最新

  • doutang6819 2018-08-23 05:47
    关注

    That's something related to lexical scoping, look over here for an introduction

    Basically any variable within {}curly braces is considered as new variable, within that block.

    so In the above program you have created two new variables.

    Block is something like enclosing a around a variable.

    If you are outside a block, you cannot see it. you need to be inside the block in order to see it.

    package main
    
    import "fmt"
    
    func main() {
        if 7%2 == 0 {
            // you are declaring a new variable,
            num := "first"
            //this variable is not visible beyond this point
        } else {
            //you are declaring a new variable,
            num := "second"
            //this variable is not visible beyond this point
        }
        // you are trying to access a variable, which is declared in someother block,
        // which is not valid, so undefined.
        fmt.Println(num)
    
    }
    

    What you are looking for is this:

    package main
    
    import "fmt"
    
    func main() {
        num := ""
        if 7%2 == 0 {
            //num is accessible in any other blocks below it
            num = "first"
        } else {
            num = "second"
        }
        //num is accessible here as well, because we are within the main block
        fmt.Println(num)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口