for_loop
package mainimport "fmt"func main() { //for init; condition; post{} 计算1-10的和 //sum := 0 //for i := 1; i <= 10; i++ { // sum += i //} //fmt.Println(sum) //1. i:=1 //2. i是否 <=10 //3. sum = 1 //4. i++ ->i =2 //5. ... //6. i=11 跳出循环 //循环字符串 name := "Wozen:我的世界" //for index, value := range name { //fmt.Println(index, value) // fmt.Printf("%d %c\n", index, value) //} //1. name 是一个字符 //2. 字符串是字符串的数组 //fmt.Printf("%c\n", name[0]) //fmt.Printf("%c\n", name[6]) name_arr := []rune(name) for i := 0; i < len(name_arr); i++ { fmt.Printf("%c\n", name_arr[i]) } //3.在做字符串遍历的时候,要尽量使用range}
goto_test
package mainimport "fmt"func main() { //goto能不用就不用 goto过多 label过多 整个程序到后期维护就会麻烦 //最容易理解的代码就是逐行的执行,哪怕你多一个函数的调用对于我们都是理解上的负担 /* 定义局部遍历 */ var a = 10 /* 循环 */LOOP: for a < 20 { if a == 15 { /* 跳过迭代 */ a = a + 1 goto LOOP } fmt.Printf("a的值为:%d\n", a) a++ }}
if_condition
package mainimport "fmt"func main() { //if语句 //num := 12 //if num%2 == 0 { // fmt.Println("偶数") //} else { // fmt.Println("奇数") //} score := 95 if score >= 90 { fmt.Println("优秀") } else if score >= 80 { fmt.Println("良") } else if score >= 60 { fmt.Println("一般") } else { fmt.Println("不及格") } //if statement;condition if num := 11; num%2 == 0 { fmt.Println("偶数") } else { fmt.Println(num) }}
switch_test
package mainimport "fmt"func main() { score := 90 grade := "A" /* 90+ A 80~90 B 70~79 C 60~69 D 60- E */ switch { case score >= 90: grade = "A" fmt.Println("优秀") case score >= 80 && score <= 89: grade = "B" case score >= 70 && score <= 79: grade = "C" case score >= 60 && score <= 69: grade = "D" default: grade = "E" } fmt.Println(grade) //不同的case表达式使用逗号分隔 var a = "daddy" switch a { case "mum", "daddy": fmt.Println("family") } var x interface{} switch i := x.(type) { case nil: fmt.Printf(" x 的类型 :%T", i) case int: fmt.Printf("x 是 int 型") case float64: fmt.Printf("x 是 float64 型") case func(int) float64: fmt.Printf("x 是 func(int) 型") case bool, string: fmt.Printf("x 是 bool 或 string 型") default: fmt.Printf("未知型") }}