table of Contents
table of Contents
@
Brief introduction
- Similar hash table or other language dictionary in the form of data stored in the key-value
- key must support == or! = Type comparison operation can not function, map or slice (they do not support), but the value can Yeah, hey
Find a map much faster than linear search, but 100 times slower (array, slice) than the type of indexed access data
Declaration defines initialization
- map supports the use of make () to create, you can create a support in the traditional way: this abbreviation =
- make ([keyType] valueType, cap), cap capacity is, can be omitted
- Automatic expansion will exceed the capacity, but to make use of an appropriate initial value
- Use len () Get the number of elements
Key-value pair does not exist automatically added, using the delete (map, key) to delete a key-value pairs
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
*/
Complex 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
*/
map and slice of iterations
/*
for i,v:=range slice/map{
}*/
//如果是slice : i是索引,int型,v是其对应的值的拷贝,对v的任何操作都不会影响slice
//如果是map : i,v对应键值对,对v的任何操作都不会影响map
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]]
*/
Use slice indirect sort of map
- map are unordered
- Introducing package sort, use sort.Ints () function
func main(){
m := map[int]string{1:"a",2:"b",3:"c",4:"d",5:"f",6:"g"}
s := make([]int, len(m))
i := 0
for 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]
*/
Examples: exchange key and 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]
*/