Go字典类型的使用

2016-06-23  本文已影响1883人  喜龙爱慧
peace&Dola Sun 作品

时光驯服一切,我与往事之间,像回声,再怎么千回百转,终究消失在山谷。 by 七堇年

引用于:http://wufazhuce.com/one/1373

map 是一种特殊的数据结构:一种元素对(pair)的无序集合,pair 的一个元素是 key,对应的另一个元素是 value,所以这个结构也称为关联数组或字典。这是一种快速寻找值的理想结构:给定 key,对应的 value 可以迅速定位。

map 这种数据结构在其他编程语言中也称为字典(Python)、hash 和 HashTable 等。

基础知识

示例

func Test_demo1(t *testing.T) {
    temp_map := map[string]int{"a": 1, "b": 2, "c": 3}

    //如果map中不存在key1,val1就是一个值类型的空值。
    fmt.Println(temp_map["d"]) //0

    //判断key是否存在
    val, ok := temp_map["d"]
    fmt.Println(ok) //false
    fmt.Println(val) //0

    val, ok = temp_map["c"]
    fmt.Println(ok) //true
    fmt.Println(val) //3

    //与if混合使用
    if _, ok = temp_map["a"]; ok {
        fmt.Println(temp_map["a"]) //1
    }

    //删除key
    delete(temp_map, "a")
    fmt.Println(temp_map) //map[b:2 c:3]

    //配合for...range使用
    for key, val := range temp_map {
        fmt.Printf("map[%s]=%d ", key, val) //map[b]=2 map[c]=3
    }
}

map 类型的切片

func Test_demo2(t *testing.T) {
    temp_slice := make([]map[string]int, 3)
    for i := range temp_slice {
        temp_slice[i] = make(map[string]int)
        temp_slice[i]["a"] = 1
    }
    fmt.Println(temp_slice) //[map[a:1] map[a:1] map[a:1]]

    //最好不要这样写
    temp_slice2 := make([]map[string]int, 3)
    for _, item := range temp_slice2 {
        item = make(map[string]int) //注意:item仅是temp_slice2内部元素的副本
        item["a"] = 1 //对item的值修改,不会影响temp_slice2内部元素的值
    }
    fmt.Println(temp_slice2) //[map[] map[] map[]]
}

map 排序

func Test_demo3(t *testing.T) {
    temp_map := map[string]int{"e": 1, "f": 2, "c": 3, "g": 4, "w": 5}
    temp_slice := make([]string, len(temp_map))

    i := 0
    for k, _ := range temp_map {
        temp_slice[i] = k
        i++
    }

    sort.Strings(temp_slice)
    for _, val := range temp_slice {
        fmt.Printf("map[%s]=%d ", val, temp_map[val])
        //map[c]=3 map[e]=1 map[f]=2 map[g]=4 map[w]=5
    }
}
上一篇 下一篇

猜你喜欢

热点阅读