1 回答

TA貢獻(xiàn)1883條經(jīng)驗 獲得超3個贊
那是與詞法作用域相關(guān)的東西,在這里查看介紹
基本上,花括號內(nèi)的任何變量都{}
被視為該塊內(nèi)的新變量。
所以在上面的程序中你創(chuàng)建了兩個新變量。
塊類似于圍繞一個變量。
如果您在街區(qū)外,則看不到它。你需要在街區(qū)內(nèi)才能看到它。
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 關(guān)注
- 128 瀏覽
添加回答
舉報