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)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。