GoLang:map

ShineLee / 2023-08-21 / 原文

学习自:GoLang学习手册100页

1、说明

map,即字典,存储一系列的K-V对,通过Key获取响应的元素。

2、定义

1)定义

dic := map[K类型]V类型{K1:V1,K2:V2,K3:V3,...}

var dic map[K类型]V类型 = map[K类型]V类型{K1:V1,K2:V2,K3:V3,...}

dic := map[int]int{0:1,1:3,2:5}
//dic为map[0:1,1:3,2:5],K为0 1 2,对应的V为1 3 5

2)说明

  • 所有可以做==、!=判断的类型都可以做K,例如(数值、字符串、数组、指针、结构体、接口
  • 不能做K的类型:slice、map、function
  • map的容量不固定,当容量不足时底层会自动扩容

3)创建(2种)

①Go语法糖:dic := map[K类型]V类型{K1:V1,K2:V2,K3:V3,...}

dict := map[string][string]{"name":"lnj","age":"33","gender":"male"}

②make:

  • dict := make(map[K类型]V类型,容量)
  • dict := make(map[K类型]V类型)
dict:=make(map[string]string,3)
dict:=make(map[string]string)//效果相同

dict["name"]="lnj"
dict["age"]="33"
dict["gender"]="male"

 

说明:

  • 只是通过var dict map[K类型]V类型定义,而没有make分配空间,是不能对往其中增删K-V对的。
//一个错误例子
var dict map[string]string
dict["name"]="lnj"//编译报错
  • 当K-V为string时,显示的时候并不会带上双引号""
dic := map[string]string{"name":"lnj"}
fpt.Println(dic)//map[name:lnj]

 

3、操作

1)修改某个K-V对:dic[K]=V_new

dic := map[int]int{0:1,1:3,2:5}
dic[1]=666 //map[0:1 1:666 2:5]

2)增加:dict[新K]=新V

dict:=make(map[string]string)//此时dict为map[ ]
dict["name"]="lnj"//此时dict为map[name:lnj]

3)删除:delete(dic,K)

delete(dict,"name")

4)查询:判断某个K-V是否存储——ok-idiom模式

dict := map[string]string{"name":"lnj","age":"33","gender":"male"}

if value,ok := dict["age'];ok {
    fmt.Println("存在age这个K,对应的V为:",value)
}
//其中ok才是判断依据
//以上写法等价于
value,ok := dict["age"]
if(ok){
    fmt.Println("存在age这个K,对应的V为:",value)
}else{
    fmt.Println("不存在age这个K,对应的V为:",value)
}

5)遍历:for key,value := range dict{对key,value的操作}

for K,V := range dict{
    fmt.Println(K,V)
}

map中的数据是无序的,所以多次打印顺序可能不同