1 回答
TA贡献1883条经验 获得超3个赞
那是与词法作用域相关的东西,在这里查看介绍
基本上,花括号内的任何变量都{}
被视为该块内的新变量。
所以在上面的程序中你创建了两个新变量。
块类似于围绕一个变量。
如果您在街区外,则看不到它。你需要在街区内才能看到它。
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)
}
你要找的是这个:
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)
}
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报