1. 程式人生 > 其它 >【Go 語言社群】Go 語言Map(集合)

【Go 語言社群】Go 語言Map(集合)

Go 語言Map(集合)

Map 是一種無序的鍵值對的集合。Map 最重要的一點是通過 key 來快速檢索資料,key 類似於索引,指向資料的值。

Map 是一種集合,所以我們可以像迭代陣列和切片那樣迭代它。不過,Map 是無序的,我們無法決定它的返回順序,這是因為 Map 是使用 hash 表來實現的。

定義 Map

可以使用內建函式 make 也可以使用 map 關鍵字來定義 Map:

/* 宣告變數,預設 map 是 nil */var map_variable map[key_data_type]value_data_type/* 使用 make 函式 */map_variable = make(map[key_data_type]value_data_type)

如果不初始化 map,那麼就會建立一個 nil map。nil map 不能用來存放鍵值對

例項

下面例項演示了建立和使用map:

package mainimport "fmt"func main() {
   var countryCapitalMap map[string]string
   /* 建立集合 */
   countryCapitalMap = make(map[string]string)
   
   /* map 插入 key-value 對,各個國家對應的首都 */
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
   
   /* 使用 key 輸出 map 值 */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* 檢視元素在集合中是否存在 */
   captial, ok := countryCapitalMap["United States"]
   /* 如果 ok 是 true, 則存在,否則不存在 */
   if(ok){
      fmt.Println("Capital of United States is", captial)  
   }else {
      fmt.Println("Capital of United States is not present") 
   }}

以上例項執行結果為:

Capital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New DelhiCapital of United States is not present

delete() 函式

delete() 函式用於刪除集合的元素, 引數為 map 和其對應的 key。例項如下:

package mainimport "fmt"func main() {   
   /* 建立 map */
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   
   fmt.Println("原始 map")   
   
   /* 列印 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")   
   
   /* 列印 map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }}

以上例項執行結果為:

原始 mapCapital of France is ParisCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New DelhiEntry for France is deleted刪除元素後 mapCapital of Italy is RomeCapital of Japan is TokyoCapital of India is New Delhi