for 循环
Loop:
for i:=0; i< 10; i++ {
for j:=0; j<10; j++ {
if i == 5 {
continue Loop
}
fmt.Println("i:",i, ";j:",j)
}
}
switch
i := 10
switch {
case i==4:
fmt.Println("4444")
case i==5:
fmt.Println("5555")
default:
fmt.Println("default:", i)
}
switch 9 {
case 9:
fmt.Println("999")
fallthrough
case 10:
fmt.Println("ok")
fallthrough// golang 默认break,如果要穿过去,用 fallthrough
default:
fmt.Println("default")
}
for key, value := range {}
字符串循环
str := "abcdefg"
for i,k := range str {// i 是索引, k 是值
fmt.Printf("%v-%v\n",i,string(k))
}
str1 := "你好,中国"
for i,k := range str1 {// unicode 为单位来读取字符串,下标值
fmt.Printf("%v-%v\n", i, string(k))
}
//0-你
//3-好
//6-,
// 9-中
//12-国
slice 切片
var sc []int
sc = make([]int, 0, 10)
// append 是往切片里添加元素
sc = append(sc, 1,2,3)
sc = append(sc, []int{4,5,6}...)
for k, v := range sc {
fmt.Println("key:",k, ";val:",v)
}
map
m := make(map[string]int)
m["a"] = 1
m["b"] = 2
m["c"] = 3
m["hello"] = 5
m["world"] = 7
m["ni"] = 6
for k, v := range m {
fmt.Println(k,v)
}
// 结果
//ni 6
//a 1
//b 2
//c 3
//hello 5
//world 7
for k, v := range m {
fmt.Println(k,v)
}
// 结果如下
//a 1
//b 2
//c 3
//hello 5
//world 7
//ni 6
从这两个打印可以看出,map的遍历是没有顺序的、随机的,不可以依赖写入的顺序