关于golang:GO的第二天学习MAP

3次阅读

共计 946 个字符,预计需要花费 3 分钟才能阅读完成。

MAP 的定义(在应用之前必须先创立)
 哈希表是一种数据结构。它是一个无序的 key/value 对的汇合,其中有的 key 都是
不同的,而后通过给定的 key 能够在常数工夫复杂度内检索、更新和删除对应的 value
在 GO 语言中,一个 map 就是一个哈希表的援用,map 类型能够写为 map[key]value。map 中所有的 key 都有雷同的类型,value 也有着雷同的类型,key 和 value 能够是不同
的类型
ages := make(map[string]int) //mapping from strings to ints
ages :=map[string]int{
    "alice":31,
    "charlie":34,
}

// 这相当于
ages :=make(map[string]int)
ages["ailce"] = 31
拜访 map 的一个元素
ages["alice"]
删除 key 对应的 value
delete(args,"alice")
遍历 map
 想要遍历 map 中全副的 key/value 对的话,能够应用 range 格调的 for 实现,和之前
的 slice 遍历语言相似。map 中的遍历并不是程序执行的,是随机的,如果想要程序
遍历 key/value 对,咱们必须显示的对 key 进行排序,
for name,age range ages {fmt.Printf("%s\t%d\n",name,age)
}    

// 程序的遍历 map
import "sort"
var names []string
// 先把 key 取出来
for index ,_ := range ages {names = append(names,index)
}
对 key 进行排序
sort.Strings(names)

查找出 key 对应的 value
for index,name :=range names {fmt.Printf("%s\t%d\n",name,ages[index]
}    
判断两个 map 是否有雷同的 key 和 value
func equal(x,y map[sting]int)bool {if len(x) != len(y) {return false}
    
    for xIndex,xValue := range x {if yValue,ok := y[xIndex]; !ok ||yValue != xValue {return false}
    }
    return true
}    
正文完
 0