Go 遍历切片以及遍历映射

Go 中几乎从不使用数组,而是使用切片 即 slice, 以下是一个切片的例子:

var mySlice []string
    mySlice = append(mySlice, "cat")
    mySlice = append(mySlice, "dog")
    mySlice = append(mySlice, "fish")
    for _, x := range mySlice {
    
    
        fmt.Println(x);
    }

遍历切片的语法:

for  index, element := range mySlice {
    
    
}

遍历映射的例子:

    intMap := make(map[string]int)
    intMap["one"] = 1
    intMap["two"] = 2
    intMap["three"] = 3
    intMap["four"] = 4
    intMap["five"] = 5
    intMap["six"] = 6
    intMap["seven"] = 7
 
    for key, value := range intMap {
    
    
        fmt.Println(key, value)
    }

判断某一个key是否存在于映射中:

el, ok := intMap["four"]
if ok == nil {
    
    
    // intMap 中不存在为 "four" 的key
}

猜你喜欢

转载自blog.csdn.net/ftell/article/details/123552807
今日推荐