go的变量作用域

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/go/191289.html

猜你在找的Go相关文章