var e int = 9 if e == 10 { fmt.Println("d == 10") } else if e > 10 { fmt.Println("e > 10") } else if e < 10 { fmt.Println("e < 10") } else { fmt.Println("这是不可能的") }
func main() { var num int fmt.Printf("please input floor number:") fmt.Scan(&num) switch num { //switch 后面是变量本身 // switch num := 5; num { //switch 支持一个初始化语句,用;分隔 case 1, 5: fmt.Println("case is 1 or 5") fallthrough // 不跳出switch语句,后面的条件无条件地执行 case 2: fmt.Println("case is :", 2) case 3: fmt.Println("case is :", 3) case 4: fmt.Println("case is :", 4) default: fmt.Println("this is default case") }
// case 判断一个表达式 var grade string fmt.Printf("please input grade:") fmt.Scan(&grade) switch { case grade == "A": fmt.Printf("优秀!\n") case grade == "B", grade == "C": fmt.Printf("良好\n") fallthrough // 不跳出switch语句,下一句case无条件地执行 case grade == "D": fmt.Printf("及格\n") fallthrough // 不跳出switch语句,下一句case无条件地执行 case grade == "F": break //跳出switch fmt.Printf("不及格\n") default: fmt.Printf("差\n") } fmt.Printf("你输入的grade:%s\n", grade)
}
for循环
格式: for 初始条件;判断条件;条件变化 {
} 或使用range迭代,下标从0开始 for index,data := range iterable_obj {
}
1 2 3 4 5
sum := 0 for i := 1; i < 10; i++ { sum = sum + i fmt.Println(sum) }
1 2 3 4
str := "abc" for i, data := range str { fmt.Printf("The No. %d element is: %c\n", i, data) }
使用_丢弃返回的下标
1 2 3 4
str := "abc" for _, data := range str { fmt.Println(data) }
丢弃返回元素,再通过下标取元素
1 2 3 4 5 6 7 8
str := "abc" for i, _ := range str { fmt.Printf("%c\n", str[i]) } //等价于: for i := range str { fmt.Printf("%c\n", str[i]) }
for后面不写任何内容,表示条件永远为值,死循环
1 2 3 4 5 6 7
for { fmt.Println(i) if i == 99999 { break } i++ }