好用的golang switch

python没有switch语句,需要对比的时候还得if ××==××;不够优雅
发现golang的switch后,觉得代码写出来又工整有优雅,赞!

package test

import (
	// "encoding/json"
	"fmt"
)

func SwitchWork(){
	test1()
	test2()
	test3()
	test4()
	comparestr("S")
}

func test1() {  
	var finger int
	fmt.Println("请伸出你的一个手指:")
	fmt.Scanln(&finger)
    switch  finger {//finger is declared in switch
		case 1:
			fmt.Println("Thumb")
		case 2:
			fmt.Println("Index")
		case 3:
			fmt.Println("Middle")
		case 4:
			fmt.Println("Ring")
		case 5:
			fmt.Println("Pinky")
		default: //default case
			fmt.Println("incorrect finger number")
	}
}

func test2() {  
    letter := "i"
    switch letter {
		case "a", "e", "i", "o", "u": //multiple expressions in case
			fmt.Println("vowel")
		default:
			fmt.Println("not a vowel")
	}
}

func test3() {  
    num := 75
    switch { // expression is omitted
		case num >= 0 && num <= 50:
			fmt.Println("You get C")
		case num >= 51 && num <= 80:
			fmt.Println("You get B")
		case num >= 81 && num <= 100:
			fmt.Println("You get A")
	}
}

func number() int {  
	num := 15 * 5 
	return num
}

func test4() {
	switch num := number(); { //num is not a constant
		case num < 50:
			fmt.Printf("%d is lesser than 50\n", num)
			fallthrough//执行完继续匹配下一个case
		case num < 100:
			fmt.Printf("%d is lesser than 100\n", num)
			fallthrough
		case num < 200:
			fmt.Printf("%d is lesser than 200\n", num)
	}
}

func comparestr(str string) {
	switch str {
		case "A" :
			fmt.Println("alpha")
		case "B" :
			fmt.Println("bravo")
		case "C" :
			fmt.Println("charlie")		
		default:
			fmt.Println(str)	
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值