golang中Switch-语句详解

switch 第一种表达式

func main() {
	num := 3
	switch num {
	case 1:
		fmt.Println("num=1")
	case 2:
		fmt.Println("num=2")
	case 3:
		fmt.Println("num=3")
	default:
		fmt.Print("没有条件成立")
	}
}

输出结果

API server listening at: 127.0.0.1:22973
num=3
Process exiting with code: 0

num := 3为全局变量

switch 第二种表达式

func main() {
	num := 3
	switch {
	case num <= 1:
		fmt.Println("<= 1")
	case num >= 2:
		fmt.Println(">= 2")
	case num >= 3:
		fmt.Println(">= 3")
	default:
		fmt.Print("没有条件成立")
	}
}

输出结果

API server listening at: 127.0.0.1:2079
>= 2
Process exiting with code: 0

num := 3为全局变量

我们可以添加fallthrough让case语句继续运行判断

func main() {
	num := 3
	switch {
	case num <= 1:
		fmt.Println("<= 1")
	case num >= 2:
		fmt.Println(">= 2")
		fallthrough
	case num >= 3:
		fmt.Println(">= 3")
	default:
		fmt.Print("没有条件成立")
	}
}

添加fallthrough后输出结果

API server listening at: 127.0.0.1:49351
>= 2
>= 3
Process exiting with code: 0

switch 第三种表达式

num := 3放入switch语句中

func main() {
	switch num := 3; {
	case num <= 1:
		fmt.Println("<= 1")
	case num >= 2:
		fmt.Println(">= 2")
		fallthrough
	case num >= 3:
		fmt.Println(">= 3")
	default:
		fmt.Print("没有条件成立")
	}
}

输出结果

API server listening at: 127.0.0.1:5593
>= 2
>= 3
Process exiting with code: 0

第三种输出与第二种输出结果一致

func main() {
	switch num := 3; {
	case num <= 1:
		fmt.Println("<= 1")

switch num := 3;只作用于switch语句中,我们最后添加一个输出语句查看是否能输出num的值

func main() {
	switch num := 3; {
	case num <= 1:
		fmt.Println("<= 1")
	case num >= 2:
		fmt.Println(">= 2")
		fallthrough
	case num >= 3:
		fmt.Println(">= 3")
	default:
		fmt.Print("没有条件成立")
	}
	fmt.Println(num)
}

输出结果

undefined: num

此结果证明在switch语句中声明变量为局部变量

原文地址:https://www.cnblogs.com/iXiAo9/p/13627765.html