zoukankan      html  css  js  c++  java
  • 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语句中声明变量为局部变量

  • 相关阅读:
    LG5283 异或粽子
    LG2216 理想的正方形
    LG1484 种树
    洛谷3721 HNOI2017单旋(LCT+set+思维)
    洛谷3348 大森林 (LCT + 虚点 + 树上差分)
    CF1082E Increasing Frequency (multiset+乱搞+贪心)
    CF1082G Petya and Graph(最小割,最大权闭合子图)
    cf1082D Maximum Diameter Graph(构造+模拟+细节)
    洛谷3320 SDOI2015寻宝游戏(set+dfs序)(反向迭代器的注意事项!)
    CF613D Kingdom and its Cities(虚树+贪心)
  • 原文地址:https://www.cnblogs.com/iXiAo9/p/13627765.html
Copyright © 2011-2022 走看看