map数据结构
key-value的数据结构,又叫字典或关联数组
- 声明:
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
样例一:
func testMap() { var a map[string]string a = make(map[string]string, 10) a["abc"] = "efg" a["abc"] = "efg" a["abc1"] = "efg" fmt.Println(a) }
样例二:
func testMap() { a := make(map[string]string, 10) a["abc"] = "efg" a["abc"] = "efg" a["abc1"] = "efg" fmt.Println(a) }
样例三:
func testMap() { var a map[string]string = map[string]string{ "key": "value", } a["abc"] = "efg" a["abc"] = "efg" a["abc1"] = "efg" fmt.Println(a) }
- 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 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 testMap4() { 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)) }
- 多层map
func testMap2() { 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" fmt.Println(a) }
- slice of map
func testMap5() { var a []map[int]int a = make([]map[int]int, 5) if a[0] == nil { a[0] = make(map[int]int) } a[0][10] = 10 fmt.Println(a) }
时间: 2024-10-11 00:48:22