什麼是map ide
map 是在go 中將值(value) 與 鍵(key) 關聯的內置類型,經過相應的鍵能夠獲取到值
定義類型爲 map[key]valuecode
1、 建立map string
```
package main
import "fmt"
func maptest() {
// 一、聲明方式1 map
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2)
// 輸出
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2) it
//二、聲明方式2 聲明一個空map map2 :=map[int] string{} fmt.Println(map2) // 輸出 map[] // 三、 聲明方式3 使用make 聲明一個map, map3 :=make(map [int]int,10) fmt.Println(map3) // 輸出 map[] 0 } func main() { maptest()
}class
2、map 的獲取
// 一、遍歷獲取
for k,v :=range map1{
fmt.Println(k,v)
}test
// 輸出 1 key1
2 key2
3 key3import
//二、判斷map 中key 值是否存在遍歷
if v,has :=map1[1];has{ fmt.Println("value=",v,"has=",has) } else{ fmt.Println("value=",v,"has=",has) // 輸出 value= key1 has= true
3、map 刪除
// 一、刪除
fmt.Println("begin delete")
delete (map1,1)
for k,v :=range map1{
fmt.Println(k,v)
}map
// 輸出 2 key2 3 key3
二、 修改
map1[1]="hello"
map1[4]="world"im
for k,v :=range map1{ fmt.Println(k,v) } // 輸出 4 world 1 hello 2 key2 3 key3