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 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办