3. Conditional judgment of GO

1. if format

if 表达式1 {
    分支1
} else if 表达式2 {
    分支2
} else{
    分支3
}

 2. switch case

func switchDemo1() {
	finger := 3
	switch finger {
	case 1:
		fmt.Println("大拇指")
	case 2:
		fmt.Println("食指")
	case 3:
		fmt.Println("中指")
	case 4:
		fmt.Println("无名指")
	case 5:
		fmt.Println("小拇指")
	default:
		fmt.Println("无效的输入!")
	}
}

It can also be followed by multiple conditions.

func testSwitch3() {
    n := 7
	switch  n {
	case 1, 3, 5, 7, 9:
		fmt.Println("奇数")
	case 2, 4, 6, 8:
		fmt.Println("偶数")
	default:
		fmt.Println(n)
	}
}

Branches can also use expressions. In this case, there is no need to follow the switch statement with a judgment variable.

func switchDemo4() {
	age := 30
	switch {
	case age < 25:
		fmt.Println("好好学习吧")
	case age > 25 && age < 35:
		fmt.Println("好好工作吧")
	case age > 60:
		fmt.Println("好好享受吧")
	default:
		fmt.Println("活着真好")
	}
}

Guess you like

Origin blog.csdn.net/qq_48480384/article/details/129930550