概述
前几篇文章分享了 array 数组、slice 切片、map 集合,这篇文章分享如何循环获取里面的元素,同时也是对前几篇文章的复习。
本篇文章会用到的关键字 for、range、break、continue、goto、switch。
循环 array
//demo_18.go package main import ( "fmt" ) func main() { person := [3] string {"Tom", "Aaron", "John"} fmt.Printf("len=%d cap=%d array=%v\n", len(person), cap(person), person) fmt.Println("") //循环 for k, v := range person { fmt.Printf("person[%d]: %s\n", k, v) } fmt.Println("") for i := range person { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") for i := 0; i < len(person); i++ { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") //使用空白符 for _, name := range person { fmt.Println("name :", name) } }
//demo_19.go package main import ( "fmt" ) func main() { person := [] string {"Tom", "Aaron", "John"} fmt.Printf("len=%d cap=%d slice=%v\n", len(person), cap(person), person) fmt.Println("") //循环 for k, v := range person { fmt.Printf("person[%d]: %s\n", k, v) } fmt.Println("") for i := range person { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") for i := 0; i < len(person); i++ { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") //使用空白符 for _, name := range person { fmt.Println("name :", name) } }
//demo_20.go package main import ( "fmt" ) func main() { person := map[int]string{ 1 : "Tom", 2 : "Aaron", 3 : "John", } fmt.Printf("len=%d map=%v\n", len(person), person) fmt.Println("") //循环 for k, v := range person { fmt.Printf("person[%d]: %s\n", k, v) } fmt.Println("") for i := range person { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") for i := 1; i <= len(person); i++ { fmt.Printf("person[%d]: %s\n", i, person[i]) } fmt.Println("") //使用空白符 for _, name := range person { fmt.Println("name :", name) } }
运行结果:
break
跳出当前循环,可⽤于 for、switch、select。
//demo_21.go package main import "fmt" func main() { for i := 1; i <= 10; i++ { if i == 6 { break } fmt.Println("i =", i) } }
//demo_22.go package main import "fmt" func main() { for i := 1; i <= 10; i++ { if i == 6 { continue } fmt.Println("i =", i) } }
//demo_23.go package main import "fmt" func main() { fmt.Println("begin") for i := 1; i <= 10; i++ { if i == 6 { goto END } fmt.Println("i =", i) } END : fmt.Println("end") }
//demo_24.go package main import "fmt" func main() { i := 1 fmt.Printf("当 i = %d 时:\n", i) switch i { case 1: fmt.Println("输出 i =", 1) case 2: fmt.Println("输出 i =", 2) case 3: fmt.Println("输出 i =", 3) fallthrough case 4,5,6: fmt.Println("输出 i =", "4 or 5 or 6") default: fmt.Println("输出 i =", "xxx") } }
运行结果:
当 i = 1 时:输出 i = 1
当 i = 2 时:输出 i = 2
当 i = 3 时:
输出 i = 3
输出 i = 4 or 5 or 6
当 i = 4 时:输出 i = 4 or 5 or 6
当 i = 7 时:输出 i = xxx
结论:
默认每个 case 带有 break
case 中可以有多个选项
fallthrough 不跳出,并执行下一个 case