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)
}
}