一、if语句
package main import "fmt" //if条件语句 func main() { var score = 63 if score >= 90 && score <= 100 { fmt.Println("A") } else if score >= 80 && score < 90 { fmt.Println("B") } else if score >= 70 && score < 80 { fmt.Println("C") } else if score >= 60 && score < 70 { fmt.Println("D") } else { fmt.Println("不及格") } }
D
二、switch语句
package main import "fmt" func main() { var score = 80 switch score { case 90: fmt.Println("A") case 80: fmt.Println("B") case 50, 60, 70: fmt.Println("C") default: fmt.Println("D") } //switch可以省略默认值,默认传true switch { case false: fmt.Println("false") case true: fmt.Println("true") default: fmt.Println("other") } }
func TestSwitchMultiCase(t *testing.T) { for i := 0; i < 5; i++ { switch i { case 0, 2: t.Log(i, "Even") case 1, 3: t.Log(i, "Odd") default: t.Log(i, "it is not 0-3") } } }
=== RUN TestSwitchMultiCase condition_test.go:16: 0 Even condition_test.go:18: 1 Odd condition_test.go:16: 2 Even condition_test.go:18: 3 Odd condition_test.go:20: 4 it is not 0-3 --- PASS: TestSwitchMultiCase (0.00s) PASS
三、fallthrough语句
package main import "fmt" func main() { flag := false switch flag { case false: fmt.Println("false") //无视下一个条件是否满足,直接执行 fallthrough case true: //防止穿透 if flag == false { break } fmt.Println("true") default: fmt.Println("default") } }
false