1、map簡介數組
key - value 的數據結構,又叫字典或者關聯數組數據結構
一、聲明(聲明是不會分配內存,初始化用make)app
var map1 map[key type] value type排序
var a map[string]string內存
var a map[string]intstring
var a map[int]stringit
var a map[string] map[string]stringtest
二、map相關操做遍歷
func testMap(){
var a map[string]string
a = make(map[string]string,10)
a["hello"] = "world" //插入和更新操做
a["hello2"] = "world2" //插入和更新操做
Val,ok := a["hello"] //查找
if ok {
for k,v := range a {
fmt.Println(k,v)
}
}
delete(a,"hello") //刪除
fmt.Println(a,Val,ok)
fmt.Println(a["hello"])
fmt.Println(len(a)) //長度
}
三、map是引用類型
func modify(a map[string]string)map[string]string{
a["hello2"] = "hello bin change"
return a
}
四、slice of map切片中包含字典
func sliceOfMap(){
items := make([]map[int]int,5)
for i := 0;i<5;i++{
items[i] = make(map[int]int)
}
fmt.Println(items)
}
五、map排序
a、先獲取全部key,把key進行排序
b、按照排序好的key,進行遍歷
示例:
func testMap2(){
var a map[string]string
a = make(map[string]string,10)
a["hello"] = "world" //插入和更新操做
a["hello3"] = "world3" //插入和更新操做
a["hello2"] = "world2" //插入和更新操做
fmt.Println(a)
var keys []string
for k,v := range a {
fmt.Printf("a[%s] = %s\n",k,v)
keys = append(keys,k)
}
fmt.Println("\n")
sort.Strings(keys) //對key進行排序
for _,k := range keys {
fmt.Printf("a[%s] = %s\n",k,a[k])
}
}
六、map反轉
初始化另一個map,把key和value互換便可
示例:
func testMap3(){
var a map[string]string
var b map[string]string
a = make(map[string]string,10)
b = make(map[string]string,10)
a["hello"] = "world" //插入和更新操做
a["hello3"] = "world3" //插入和更新操做
a["hello2"] = "world2" //插入和更新操做
for k,v :=range a {
b[v] = k
}
fmt.Println(a)
fmt.Println(b)
}