map是一种无序的基于key-value的数据结构,Go语言中的map是引用类型,必须初始化才能使用
1.map基本使用
map[KeyType]ValueType
● KeyType:表示键的类型。
● ValueType:表示键对应的值的类型。
m := make(map[string]int,8)
m["k1"] = 10
m["k2"] = 20
fmt.Println(m)
fmt.Println(m["k1"])
user :=map[string]string{
"username":"cheng",
"password":"wdnmd",
}
fmt.Println(user)
2.判断某个键是否存在
value, ok := map[key]
m := make(map[string]int,8)
m["k1"] = 10
m["k2"] = 20
value,ok :=m["k1"]
if ok {
fmt.Println(value)
}else {
fmt.Println("没有")
}
3.map的遍历
m := make(map[string]int,8)
m["k1"] = 10
m["k2"] = 20
m["k3"] = 30
m["k4"] = 40
m["k5"] = 50
for k, v := range m {
fmt.Println(k,v)
}
4.使用delete()函数删除键值对
使用delete()内建函数从map中删除一组键值对
delete(map, key)
map:表示要删除键值对的map
key:表示要删除的键值对的键
m := make(map[string]int)
m["k1"] = 10
m["k2"] = 20
m["k3"] = 30
m["k4"] = 40
m["k5"] = 50
delete(m,"k1")
fmt.Println(m) //map[k2:20 k3:30 k4:40 k5:50]
5.按照指定顺序遍历map
var m = make(map[string]int,200)
for i := 0; i < 100; i++ {
key := fmt.Sprintf("stu%02d", i)
value := rand.Intn(100)
m[key] = value
}
for k, v := range m {
fmt.Println(k,v)
}
//无序
stu00 81
stu03 59
stu01 87
stu07 40
stu09 0
stu05 18
stu08 56
stu06 25
stu02 47
stu04 81
var m = make(map[string]int,20)
for i := 0; i < 10; i++ {
key := fmt.Sprintf("stu%02d", i
value := rand.Intn(100)
m[key] = value
}
var keys = make([]string,0,10)
for key, _ := range m {
keys=append(keys, key)
}
sort.Strings(keys)
//按照排序后的key遍历map
for _, key := range keys {
fmt.Println(key,m[key])
}
6.元素为map类型的切片
var slice = make([]map[string]string,3)
for index, value:= range slice {
fmt.Println(index,value)
}
//0 map[]
//1 map[]
//2 map[]
var slice = make([]map[string]string,3)
for index, value:= range slice {
fmt.Println(index,value)
}
//对切片中的map元素进行初始化
slice[0] = make(map[string]string,10)
slice[0]["name"] = "cheng"
slice[0]["password"] = "123456"
fmt.Println(slice[0])
7.值为切片类型的map
var m = make(map[string][]string,3)
fmt.Println(m)
key := "中国"
value,ok :=m[key]
if !ok {
value = make([]string,0,2)
}
value=append(value,"香港","台湾")
m[key] = value
fmt.Println(m)