key-value的数据结构,又叫字典或关联数组(map是无序的)
创新互联建站服务项目包括涟源网站建设、涟源网站制作、涟源网页制作以及涟源网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,涟源网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到涟源省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!
声明:
var map1 map[keytype]valuetype
var a map[string]string
var a map[string]int
var a map[int]string
var a map[string]map[string]string
声明是不会分配内存的,初始化需要make
创建方式:
package main
import "fmt"
func main() {
a := make(map[string]string, 10)
fmt.Println(a)
a["a"] = "aa"
a["b"] = "bb"
fmt.Println(a)
var b map[string]string = map[string]string {
"b1": "v1",
"b2": "v2",
}
fmt.Println(b)
var c = map[string]string {
"c1": "v1",
"c2": "v2",
}
fmt.Println(c)
d := map[string]string {
"d1": "v1",
"d2": "v2",
}
fmt.Println(d)
}
输出:
map[]
map[a:aa b:bb]
map[b1:v1 b2:v2]
map[c1:v1 c2:v2]
map[d1:v1 d2:v2]
Process finished with exit code 0
map相关操作:
var a map[string]string = map[string]string{“hello”: “world”}
a = make(map[string]string, 10)
a[“hello”] = “world”//插入和更新
Val, ok := a[“hello”]//查找
for k, v := range a {//遍历
fmt.Println(k,v)
}
delete(a, “hello”)//删除
len(a)//长度
查找/修改的用法举例:
func modify(a map[string]map[string]string) {
_, ok := a["zhangsan"]
if !ok {
//要记得初始化(是map类型的)值
a["zhangsan"] = make(map[string]string)
}
a["zhangsan"]["passwd"] = "123456"
a["zhangsan"]["nickname"] = "pangpang"
return
}
func testMap3() {
a := make(map[string]map[string]string, 100)
modify(a)
fmt.Println(a)
}
func main() {
testMap3()
}
遍历值为map的map:
package main
import "fmt"
func trans(a map[string]map[string]string) {
for k, v := range a {
fmt.Println(k)
for k1, v1 := range v {
fmt.Println("\t", k1, v1)
}
}
}
func main() {
a := make(map[string]map[string]string, 100)
a["key1"] = make(map[string]string)
a["key1"]["key2"] = "abc"
a["key1"]["key3"] = "abc"
a["key1"]["key4"] = "abc"
a["key1"]["key5"] = "abc"
a["key2"] = make(map[string]string)
a["key2"]["key2"] = "abc"
a["key2"]["key3"] = "abc"
trans(a)
delete(a, "key1")
fmt.Println()
trans(a)
fmt.Println(len(a))
}
输出:
key1
key2 abc
key3 abc
key4 abc
key5 abc
key2
key2 abc
key3 abc
key2
key2 abc
key3 abc
1
Process finished with exit code 0
map是引用类型
func modify(a map[string]int) {
a[“one”] = 134
}
slice of map:
Items := make([]map[int][int], 5)
For I := 0; I < 5; i++ {
items[i] = make(map[int][int])
}
map排序:
a. 先获取所有key,把key进行排序
b. 按照排序好的key,进行遍历
map反转:
a. 初始化另外一个map,把key、value互换即可
map的值也可以是map:
a := make(map[string]map[string]string, 10)
/*//报错!作为值的map[string]string也要初始化才行
a["k1"]["k2"] = "哈哈"
fmt.Println(a)*/
//作为值的map[string]string也要初始化才行!
a["k1"] = make(map[string]string)
a["k1"]["k2"] = "哈哈"
a["k1"]["k3"] = "呵呵"
a["k1"]["k4"] = "嘿嘿"
fmt.Println(a)