# go的变量作用域

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```

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传
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```