golang中map增刪改查的示例代碼
map 一種無序的鍵值對, 它是數(shù)據(jù)結(jié)構(gòu) hash 表的一種實現(xiàn)方式。map工作方式就是:定義鍵和值,并且可以獲取,設(shè)置和刪除其中的值。
聲明
// 使用關(guān)鍵字 map 來聲明
bMap := map[string]int{"key1": 18}
// 使用make來聲明
cMap := make(map[string]int)
cMap["key2"] = 19
fmt.Println("bMap:", bMap)
fmt.Println("cMap:", cMap)
上面程序用兩種方式創(chuàng)建了兩個 map,運行結(jié)果如下:
bMap: map[key1:18]
cMap: map[key2:19]
檢索鍵的值
檢索 Map元素的語法為map[key]
aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
fmt.Println("aMap:", aMap)
fmt.Println("aMapkey2:", aMap["key2"])
fmt.Println("aMapkey3:", aMap["key3"])
當map中不存在該key時,該映射將返回該元素類型的零值。所以以上程序輸出為:
aMap: map[key1:18 key2:19]
aMapkey2: 19
aMapkey3: 0
檢索鍵是否存在
檢索鍵是否存在的語法為value, ok := map[key]
aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
value, ok := aMap["key3"]
if ok {
fmt.Println("key3", value)
} else {
fmt.Println("key3", "no")
}
ok的值為map中是否存在該key,存在為true,反之為false。所以以上程序輸出為:key3 no
遍歷 Map中的所有元素
可以用for循環(huán)的range形式用于迭代 Map的所有元素。
aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
for key, value := range aMap {
fmt.Printf("aMap[%s] = %d\n", key, value)
}
以上程序輸出為:
aMap[key1] = 18
aMap[key2] = 19
因為 map 是無序的,因此對于程序的每次執(zhí)行,不能保證使用 for range 遍歷 map 的順序總是一致的,而且遍歷的順序也不完全與元素添加的順序一致。
從 Map中刪除元素
delete(map, key) 用于刪除 map 中的鍵。delete 函數(shù)沒有返回值。
aMap := make(map[string]int)
aMap["key1"] = 18
aMap["key2"] = 19
fmt.Println("map before deletion", aMap)
delete(aMap, "key1")
fmt.Println("map after deletion", aMap)
以上程序輸出為:
map before deletion map[key1:18 key2:19]
map after deletion map[key2:19]
到此這篇關(guān)于golang中map增刪改查的示例代碼的文章就介紹到這了,更多相關(guān)golang map增刪改查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang 檢查網(wǎng)絡(luò)狀態(tài)是否正常的方法
今天小編就為大家分享一篇golang 檢查網(wǎng)絡(luò)狀態(tài)是否正常的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
一個簡單的Golang實現(xiàn)的HTTP Proxy方法
今天小編就為大家分享一篇一個簡單的Golang實現(xiàn)的HTTP Proxy方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08

