您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。