From 1576d64ec1bdd311e8ad7e1132217c02d708b38e Mon Sep 17 00:00:00 2001 From: lifeilin01 Date: Sun, 23 May 2021 19:08:50 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E5=A2=9E=E5=8A=A0=E9=A2=98=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + question/q022.md | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 question/q022.md diff --git a/README.md b/README.md index c47fc1b..8aa552b 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ - [简单聊聊内存逃逸?](question/q019.md) - [字符串转成byte数组,会发生内存拷贝吗?](question/q020.md) - [http包的内存泄漏](question/q021.md) +- [sync.Map 的用法](question/q022.md) ## Golang 理论 diff --git a/question/q022.md b/question/q022.md new file mode 100644 index 0000000..6e34ac7 --- /dev/null +++ b/question/q022.md @@ -0,0 +1,34 @@ +# sync.Map 的用法 + +## 问题 + +```go +package main + +import ( + "fmt" + "sync" +) + +func main(){ + var m sync.Map + m.Store("address",map[string]string{"province":"江苏","city":"南京"}) + v,_ := m.Load("address") + fmt.Println(v["province"]) +} +``` + +- A,江苏; +- B`,v["province"]`取值错误; +- C,`m.Store`存储错误; +- D,不知道 + +## 解析 + +`invalid operation: v["province"] (type interface {} does not support indexing)` +因为 `func (m *Map) Store(key interface{}, value interface{})` +所以 `v`类型是 `interface {}` ,这里需要一个类型断言 + +```go +fmt.Println(v.(map[string]string)["province"]) //江苏 +```