不積跬步,無以至千里;不積小流,無以成江海。
Go語言中提供的映射關係容器為 map,其內部使用散列表(hash)實現。
map是一種無序的基於key-value的數據結構,Go語言中的map是 引用類型,( )必須 初始化才能使用。
map定義
map的定義語法如下:
map[KeyType]ValueType
- KeyType:表示鍵的類型。
- ValueType:表示鍵對應的值的類型。
map類型的變量默認初始值為 nil,需要使用 make() 函數來分配內存。語法為:
make(map[KeyType]ValueType, [cap])
其中cap表示map的 容量,該參數雖然 不是必須 的,但是我們應該在初始化map的時候就為其指定一個合適的容量。
map 基本使用
map中的數據都是 成對
出現的,map的基本使用示例代碼如下:<code>func
main
() {scoreMap
:=make
(map[string]int,8
) scoreMap["張三"
] =100
scoreMap["李四"
] =90
fmt.Println
(scoreMap) fmt.Println
(scoreMap["李四"
]) fmt.Printf
("type of a:%T\n"
, scoreMap) } /<code>
輸出:
<code>map
[張三:100
李四:90
]90
type
of a:map
[string
]int
/<code>
map也支持在聲明的時候填充元素,例如:
<code>userInfo :=map
[string
]string
{"username"
:"admin"
,"password"
:"123456"
, } fmt.Println(userInfo) /<code>
判斷某個鍵是否存在
Go語言中有個判斷map中鍵是否存在的特殊寫法,格式如下:
value, ok := map[key]
<code>func
main
()
{ scoreMap :=make
(map
[string
]int
) scoreMap["張三"
] =90
scoreMap["李四"
] =100
v, ok := scoreMap["張三"
]if
ok { fmt.Println(v) }else
{ fmt.Println("查無此人"
) } } /<code>
map 遍歷
Go語言中也是使用for range遍歷map。
<code>func
main
() {scoreMap
:=make
(map[string]int) scoreMap["張三"
] =90
scoreMap["李四"
] =100
scoreMap["趙四"
] =60
for k, v := range scoreMap { fmt.Println
(k, v) } } /<code>
輸出
<code>趙四
80
張三
100
李四
90
/<code>
注意: 遍歷map時的元素順序與添加鍵值對的順序無關。
使用delete()函數刪除鍵值對
使用delete()內建函數從map中刪除一組鍵值對,delete()函數的格式如下:
delete(map, key)
- map:表示要刪除鍵值對的map
- key:表示要刪除的鍵值對的鍵
<code>func
main
(){scoreMap
:=make
(map[string]int) scoreMap["張三"
] =90
scoreMap["李四"
] =100
scoreMap["趙四"
] =60
delete
(scoreMap,"趙四"
)//將趙四:60
從map中刪除 for k,v := range scoreMap{ fmt.Println
(k, v) } } /<code>
按照指定順序遍歷map
<code>rand.Seed(time.Now().UnixNano())var
scoreMap =make
(map
[string
]int
,200
)for
i :=0
; i100
; i++ { key := fmt.Sprintf("stu%02d"
, i) value := rand.Intn(100
) scoreMap[key] = value }var
keys =make
([]string
,0
,200
)for
key :=range
scoreMap { keys =append
(keys, key) } sort.Strings(keys)for
_, key :=range
keys { fmt.Println(key, scoreMap[key]) } /<code>
元素為map類型的切片
<code>func
main
()
{var
mapSlice =make
([]map
[string
]string
,3
)for
index, value :=range
mapSlice { fmt.Printf("index:%d value:%v\n"
, index, value) } fmt.Println("after init"
) mapSlice[0
] =make
(map
[string
]string
,10
) mapSlice[0
]["name"
] ="admin"
mapSlice[0
]["password"
] ="123456"
mapSlice[0
]["age"
] ="20"
for
index, value :=range
mapSlice { fmt.Printf("index:%d value:%v\n"
, index, value) } } /<code>
輸出:
<code>0map
[]
1map
[]
2map
[]
after
init
index
:0
value
:map
[age:20 name:admin password:123456]
index
:1
value
:map
[]
index
:2
value
:map
[]
/<code>
值為切片類型的map
<code>var
sliceMap =make
(map
[string
][]string
,3
) fmt.Println(sliceMap) fmt.Println("after init"
) key :="中國"
value, ok := sliceMap[key]if
!ok { value =make
([]string
,0
,2
) } value =append
(value,"北京"
,"上海"
) sliceMap[key] = value fmt.Println(sliceMap) /<code>
輸出:
<code>map
[] afterinit
map
[中國:[北京 上海]] /<code>
點關注 不迷路
如果你從本篇內容有收穫,求 點贊,求 關注,求 轉發 ,讓更多的人學習到。
如果本文有任何錯誤,請批評指教,不勝感激