先上代码……
package main import "fmt" func testMap() { //两种声明map方式,切记,必须初始化才能用,否则panic //var a map[string]string = map[string]string{ // "key": "value", //} a := make(map[string]string, 10) a["abc"] = "efg" //map的key是唯一的,修改值可以直接改 a["abc"] = "efg2" a["abc1"] = "efg" fmt.Println(a) } //map嵌套map //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) } func modify(a map[string]map[string]string) { _, ok := a["zhangsan"] if !ok { a["zhangsan"] = make(map[string]string) } //与_,ok写法一样 //if a["zhangsan"] == nil {} // 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 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" //删除map键的内置函数delete //delete(a,"key1") trans(a) fmt.Println(len(a)) } func testMap5() { var a []map[int]int a = make([]map[int]int, 5) //for i:=0;i<5;i++{} //map,slice判断空是nil if a[0] == nil { a[0] = make(map[int]int) } a[0][10] = 10 fmt.Println(a) } func main() { testMap() testMap2() testMap3() testMap4() testMap5() }
map反转
package main import ( "fmt" "sort" ) func testMapSort() { var a map[int]int a = make(map[int]int, 5) a[8] = 10 a[3] = 10 a[2] = 10 a[1] = 10 a[18] = 10 var keys []int for k, _ := range a { keys = append(keys, k) } sort.Ints(keys) for _, v := range keys { fmt.Println(v, a[v]) } } //map反转 func testMapSort1() { var a map[string]int var b map[int]string a = make(map[string]int, 5) b = make(map[int]string, 5) a["abc"] = 101 a["efg"] = 10 for k, v := range a { b[v] = k } fmt.Println(b) } func main() { //testMapSort() testMapSort1() }