Map

  • Like Dictionary. Is Key-Value
  • Speed: a[index]>map
  • Use make()
  • Use for range
 var m map[int]string //[key type] value type
 m = map[int]string{}
var m map[int]string = make(map[int]string)
m := make(map[int]string)
m[1]="Apple"
m[2]="Banana"

delete(m,2)

r:=m[1] //Apple
m // map[1:Apple,2:Banana]

複雜型

 var m map[int]map[int]string
 m=make(map[int]map[int]string)
 m[1]=make(map[int]string) //Init Second
 a := m[1][1]="Apple"
 b := m[2][1]+"Banana"
 fmt.Println(a) //"Apple"
 var m map[int]map[int]string
 m=make(map[int]map[int]string)
 a, ok :=m[2][1]
 if !ok {
      make[2]=make(map[int]string)
 }
 m[2][1]="test" //多返回值
 a,ok=m[2][1]
 fmt.Println(a,ok) //" " "false"
                    //"test" "true"

循環操作

 for i,v := range slice{
      
 } 
 // i為index,索引
 // v為value,值
 for k,v := range map{
      
 } 
 // k為key
 // v為value,值

example

 sm:=make([]map[int]string,5)
 for i:=range sm{
      sm[i]=make(map[int]string,1) //初始化
      sm[i][]="apple"
      fmt.Println(sm[i]) 
      // map[1:apple] map[1:apple] map[1:apple] map[1:apple] map[1:apple]
 }
 fmt.Println(sm)
 //map[1:apple] map[1:apple] map[1:apple] map[1:apple] map[1:apple]

排序、根據KEY取出MAP有序的值

import(
     "soft"
)
     m:=map[int]string(1:"a",2:"b",3:"c",4:"d",5:"e")
     s:=make([]int,len(m))

     i :=0
     for k,_ := range m{
          s[i]=k
          i++
     }
     sort.Ints(s) 
     fmt.Println(s) //1 2 3 4 5 

KEY VALUE 對調

 m1:=map[int]string{1:="a",2:="b",3:="c",4:="d",5:="e"}
      fmt.Println(m1)
 m2 := make(map[string]int)
  //map[1:a 2:b 3:c 4:d 5:e]

 for k,v := range m1 {
      m2[v]=k
 }
      fmt.Println(m2)
 //map[a:1 b:2 c:3 d:4 e:5]