for range 遍历规律
字符串、数组、切片,返回下标、值
map返回key、val
channel只返回通道内的值
举例
func ForArrayTest() { fmt.Println("for range: str") str := "hello" for key, val := range str { fmt.Println(key, val) } fmt.Println("for range: array") array := [3]int {1,2,3} for key, val := range array { fmt.Println(key, val) } fmt.Println("for range: slice") slice := []int {1,2,3} for key, val := range slice { fmt.Println(key, val) } fmt.Println("for range: map") provinceCapital := make(map[string]string) provinceCapital["山东"] = "济南" provinceCapital["河北"] = "石家庄" provinceCapital["广东"] = "广州" for key, val := range provinceCapital { fmt.Println(key, val) } fmt.Println("for range: chan") cha1 := make(chan int, 3) cha1 <- 1 cha1 <- 2 cha1 <- 3 //cha1 <- 4 for val := range cha1 { fmt.Println(val) } }
输出
for range: str 0 104 1 101 2 108 3 108 4 111 for range: array 0 1 1 2 2 3 for range: slice 0 1 1 2 2 3 for range: map 山东 济南 河北 石家庄 广东 广州 for range: chan 1 2 3 fatal error: all goroutines are asleep - deadlock!