go隨聊-map
阿新 • • 發佈:2018-12-18
定義map並初始化,根據key獲取value
items := map[string]string{
"id1": "1",
"id2": "2",
"id3": "3",
}
v:= items["id2"]
fmt.Println(v)
通過make進行構建
items:=make(map[string]string,10)
items["id1"] = "1"
items["id2"] = "2"
items["id3"] = "3"
for k,v:=range items {
fmt.Println(k,"=",v)
}
通過==進行賦值
items:=map[string]string{} items["id1"] = "1" items["id2"] = "2" items["id3"] = "3" fmt.Println(len(items))
通過delete刪除
items:=map[string]string{}
items["id1"] = "1"
items["id2"] = "2"
items["id3"] = "3"
fmt.Println(len(items))
delete(items, "id2")
fmt.Println(len(items))
map的range遍歷
items:=map[string]string{} items["id1"] = "1" items["id2"] = "2" items["id3"] = "3" for k,v:=range items { fmt.Println(k,"=",v) }
判斷key是否存在
items:=make(map[string]string,10)
items["id1"] = "1"
items["id2"] = "2"
items["id3"] = "3"
value,ok:=items["id4"]
if ok {
fmt.Println(value)
}else{
fmt.Println("不存在")
}
------------------------------
不存在
map不是執行緒安全的
var items=make(map[string]string,10) func main() { items["id1"] = "1" items["id2"] = "2" items["id3"] = "3" go process() //遍歷列印key-value值 for{ for k,v:=range items { fmt.Println(k,"=",v) } } } func process() { //一直對map進行插入、刪除操作 for { items["id1"]="1" delete(items,"id1") } } ------------------------------------------------------------ fatal error: concurrent map iteration and map write