go的变量作用域是花括号确定的,任一变量的作用域只在自身所处的花括号范围内
if, for等可以有初始化表达式的,其作用域还要高于其后的花括号一层
package main func main() { x:=1 println(x) for x:=3;;{ print(x," ") break } println(x) if x:=5; true { print(x," ") } println(x) for { x:=7 print(x," ") break } println(x) if true { x:=9 print(x," ") } println(x) if x:=2; true { print(x," ") x:="abc" print(x," ") } println(x) for x:=4;; { print(x," ") x:="def" print(x," ") break } println(x) } // 1 // 3 1 // 5 1 // 7 1 // 9 1 // 2 abc 1 // 4 def 1
有疑问加站长微信联系(非本文作者)