1.1 map定义
mapkey索引value
maphashhash table
varmapnamemap[keytype]valuetype
mapnamemapkeytypevaluetype
1.2 map的使用和概念
mapmap
package main
import "fmt"
func main() {
var maplist map[string]int
maplist["one"] = 1
fmt.Println(maplist)
}
//报错:panic: assignment to entry in nil map
//map需要先初始化内存后使用
正确做法:
package main
import "fmt"
func main() {
var maplist map[string]int
maplist = map[string]int{"one": 1, "two": 2}
maplist["three"] = 3
fmt.Println(maplist)
}
//map[one:1 three:3 two:2]
当然也可以这样子:
package main
import "fmt"
func main() {
maplist := make(map[string]int)//初始化内存了,想赋值就赋值
maplist["three"] = 3
fmt.Println(maplist)
}
mapmakemap
maplist := map[string]int{}
fmt.Println(maplist)
1.3 map的容量
mapkey-value
maplist := make(map[string]float, 100)
map
map
maplist1 := make(map[int][]int)
maplist2 := make(map[int]*[]int)
golangmapstructintstring切片数组
1.4 map的使用
1.4.1 map的遍历
scene := make(map[string]int)
scene["route"] = 66
scene["brazil"] = 4
scene["china"] = 960
for k, v := range scene {
fmt.Println(k, v)
}
1.4.2 map的删除和断言
package main
import "fmt"
func main() {
maplist := make(map[string]int)
// 准备map数据
maplist["LYY"] = 66
maplist["520"] = 4
maplist["666"] = 960
delete(maplist, "666")
for k, v := range maplist {
fmt.Println(k, v)
}
}
1.5 map的坑
package main
import "fmt"
func main() {
m := map[int]struct{}{
1: {},
2: {},
3: {},
4: {},
5: {},
}
for k := range m {
fmt.Println(k)
}
}
//没有设置v值的时候,map的遍历是随机的,起始遍历是个随机值
执行第一次:
执行第二次:
注意:map在增加值、删除时需要加互斥锁
2 并发安全map
2.1 不安全原因
goroutine
package main
import (
"fmt"
"time"
)
var TestMap map[string]string
func init() {
TestMap = make(map[string]string, 1)
}
func main() {
for i := 0; i < 1000; i++ {
go Write("aaa")
go Read("aaa")
go Write("bbb")
go Read("bbb")
}
time.Sleep(5 * time.Second)
}
func Read(key string) {
fmt.Println(TestMap[key])
}
func Write(key string) {
TestMap[key] = key
}
//报错 fatal error: concurrent map writes
mapgolang fatal error: concurrent map writes
2.2 解决方案
(1)在写操作的时候增加锁,删除时候除了加锁外,还需要增加断言避免出现错误
package main
import (
"fmt"
"sync"
)
func main() {
var lock sync.Mutex
var maplist map[string]int
maplist = map[string]int{"one": 1, "two": 2}
lock.Lock()
maplist["three"] = 3
lock.Unlock()
fmt.Println(maplist)
}
执行结果:
(2)sync.Map包
package main
import (
"fmt"
"sync"
)
func main() {
m := sync.Map{} //或者 var mm sync.Map
m.Store("a", 1)
m.Store("b", 2)
m.Store("c", 3) //插入数据
fmt.Println(m.Load("a")) //读取数据
m.Range(func(key, value interface{}) bool { //遍历
fmt.Println(key, value)
return true
})
}
执行结果:
我们称其为并发安全的map。