func main(){
var m map[int]string = map[int]string{}
var mm map[int]string = make(map[int]string)
mmm := make(map[int]string)
m[1] = "ok"
a := m[1]
fmt.Println(m,a,mm,mmm)
delete(m,1)
fmt.Println(m,a)
}
/*
> Output:
command-line-arguments
map[1:ok] ok map[] map[]
map[] ok
*/
复杂map
func main(){
var m map[int]map[int]string
m = make(map[int]map[int]string)
//这里记得里面的value对应的map也要初始化
a, ok := m[2][1]
if !ok {
m[2] = make(map[int]string)
}
m[2][1]="GOOD"
a,ok = m[2][1]
fmt.Println(a, ok)
}
/*
> Output:
command-line-arguments
GOOD true
*/
func main(){
sm := make([]map[int]string, 5)
for_, v := range sm {
v = make(map[int]string, 1)
v[1]="ok"
fmt.Println(v)
}
fmt.Println(sm)
for i := range sm {
sm[i] = make(map[int]string, 1)
sm[i][1] = "not ok"
fmt.Println(sm[i])
}
fmt.Println(sm)
}
/*
> Output:
command-line-arguments
map[1:ok]
map[1:ok]
map[1:ok]
map[1:ok]
map[1:ok]
[map[] map[] map[] map[] map[]]
map[1:not ok]
map[1:not ok]
map[1:not ok]
map[1:not ok]
map[1:not ok]
[map[1:not ok] map[1:not ok] map[1:not ok] map[1:not ok] map[1:not ok]]
*/
利用slice对map进行间接排序
map是无序的
引入包sort,使用sort.Ints()函数
func main(){
m := map[int]string{1:"a",2:"b",3:"c",4:"d",5:"f",6:"g"}
s := make([]int, len(m))
i := 0for k,_ := range m {
s[i] = k
i++
}
sort.Ints(s)
for _,v := range s {
fmt.Println(m[v])
}
fmt.Println(s)
}
/*
> Output:
command-line-arguments
a
b
c
d
f
g
[1 2 3 4 5 6]
*/
例子:交换key和value
func main(){
m := map[int]string{1:"a",2:"b",3:"c",4:"d",5:"f",6:"g"}
mm := make(map[string]int,len(m))
for k,v := range m {
mm[v]=k
}
fmt.Println(m)
fmt.Println(mm)
}
/*
> Output:
command-line-arguments
map[5:f 6:g 1:a 2:b 3:c 4:d]
map[f:5 g:6 a:1 b:2 c:3 d:4]
*/