1.map是一种key-value数据结构
又称为字段或关联数组
声明:
var 名 map[keytype]valuetype
注意:key不可以是slice、map、func
通常用到int、string
声明不会分配内存,初始化需要make才能赋值和使用
var a map[string]string
// 需要make给map分配空间
a = make(map[string]string, 10)
a["no1"] = "SongJiang"
a["no2"] = "h Ma"
// key 不能重复 value可以重复
a["no1"] = "x Li"
a["no3"] = "x Sun"
fmt.Println(a)
map一定要make
key不能重复,以最后一次赋值为准
map是无序的
2.map的删除元素
delete
cities := make(map[string]string)
cities["no1"] = "beijing"
cities["no2"] = "shanghai"
cities["no3"] = "guangzhou"
delete(cities, "no3")
delete(cities, "notExisted")
fmt.Println(cities)
key不存在,不操作、也不报错
一次删除所有值
cities := make(map[string]string)
cities["no1"] = "beijing"
cities["no2"] = "shanghai"
cities["no3"] = "guangzhou"
delete(cities, "no3")
delete(cities, "notExisted")
fmt.Println(cities)
cities = make(map[string]string)
// 重新make 一次清除所有值
// 原来的空间成为垃圾被gc回收
fmt.Println(cities)
3.map的查找
cities := make(map[string]string)
cities["no1"] = "beijing"
cities["no2"] = "shanghai"
cities["no3"] = "guangzhou"
fmt.Println(cities)
val, ok := cities["no1"]
if ok {
fmt.Println("val =", val)
} else {
fmt.Println("Not found.")
}
4.map的遍历只能用for-range
cities := make(map[string]string)
cities["no1"] = "beijing"
cities["no2"] = "shanghai"
cities["no3"] = "guangzhou"
fmt.Println("有", len(cities), "对key-value")
for k, v := range cities {
fmt.Printf("key=%v val=%v\n", k, v)
}
5.map切片
// silce of map
//slice也要make
monsters := make([]map[string]string, 2)
if monsters[0] == nil {
monsters[0] = make(map[string]string, 2)
monsters[0]["name"] = "kalsuzard"
monsters[0]["age"] = "145"
}
fmt.Println(monsters)
//append动态添加
newMonster := map[string]string{
"name": "ragnaros",
"age": "54",
}
monsters = append(monsters, newMonster)
fmt.Println(monsters)
6.对key排序
mp := make(map[int]int, 10)
mp[2] = 12
mp[3] = 323
mp[23] = 1222
mp[12] = 1220
fmt.Println(mp)
var keys []int
for k, _ := range mp {
keys = append(keys, k)
}
sort.Ints(keys)
fmt.Println(keys)
for _, k := range keys{
fmt.Printf("mp[%v] = %v\n", k, mp[k])
}
7.map是引用类型,函数接收map后修改 会修改原值
8.map想增加元素,会自动扩容 方便!