亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

watak

Go 語(yǔ)言Map(集合)


Map 是一種無(wú)序的鍵值對(duì)的集合。Map 最重要的一點(diǎn)是通過(guò) key 來(lái)快速檢索數(shù)據(jù),key 類(lèi)似于索引,指向數(shù)據(jù)的值。

Map 是一種集合,所以我們可以像迭代數(shù)組和切片那樣迭代它。不過(guò),Map 是無(wú)序的,我們無(wú)法決定它的返回順序,這是因?yàn)?Map 是使用 hash 表來(lái)實(shí)現(xiàn)的。

定義 Map

可以使用內(nèi)建函數(shù) make 也可以使用 map 關(guān)鍵字來(lái)定義 Map:


var map_variable map[key_data_type]value_data_type


map_variable = make(map[key_data_type]value_data_type)

如果不初始化 map,那么就會(huì)創(chuàng)建一個(gè) nil map。nil map 不能用來(lái)存放鍵值對(duì)

實(shí)例

下面實(shí)例演示了創(chuàng)建和使用map:

package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
   
   countryCapitalMap = make(map[string]string)
   
   
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
   
   
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   
   captial, ok := countryCapitalMap["United States"]
   
   if(ok){
      fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present") 
   }
}

以上實(shí)例運(yùn)行結(jié)果為:

Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United States is not present

delete() 函數(shù)

delete() 函數(shù)用于刪除集合的元素, 參數(shù)為 map 和其對(duì)應(yīng)的 key。實(shí)例如下:

package main

import "fmt"

func main() {   
   
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   
   fmt.Println("原始 map")   
   
   
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
   
   fmt.Println("刪除元素后 map")   
   
   
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}

以上實(shí)例運(yùn)行結(jié)果為:

原始 map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
刪除元素后 map
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi

關(guān)于我們 聯(lián)系我們 留言板

手冊(cè)網(wǎng)

Artikel sebelumnya: Artikel seterusnya: