go map 學習

什麼是map

map 是在go 中將值(value) 與 鍵(key) 關聯的內置類型,通過相應的鍵可以獲取到值
定義類型爲 map[key]value

一、 創建map

```

package main
import "fmt"
func maptest() {
// 1、聲明方式1 map
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2)
// 輸出
map2 :=map[int] string{1:"hello",2:"world"}
fmt.Println(map2)

//2、聲明方式2  聲明一個空map 

map2 :=map[int] string{}
fmt.Println(map2) 
// 輸出
map[]

// 3、 聲明方式3 使用make 聲明一個map,
map3 :=make(map [int]int,10)
fmt.Println(map3)
// 輸出
map[] 0

}

func main()  {
maptest()

}

二、map 的獲取

// 1、遍歷獲取
for k,v :=range map1{
fmt.Println(k,v)
}

// 輸出

1 key1

2 key2
3 key3

//2、判斷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

三、map 刪除

// 1、刪除
fmt.Println("begin delete")
delete (map1,1)
for k,v :=range map1{
fmt.Println(k,v)
}

 // 輸出
 2 key2
3 key3

2、 修改
map1[1]="hello"
map1[4]="world"

for k,v :=range map1{
    fmt.Println(k,v)
}

// 輸出

 4 world
 1 hello
 2 key2
3 key3
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章