Go-maps

提供:Dev Guides
移動先:案内検索

Go-マップ

Goは、一意のキーを値にマップするmapという名前の別の重要なデータ型を提供します。 キーは、後で値を取得するために使用するオブジェクトです。 キーと値を指定すると、その値をMapオブジェクトに保存できます。 値を保存したら、そのキーを使用して値を取得できます。

マップの定義

マップを作成するには、 make 関数を使用する必要があります。

/* declare a variable, by default map will be nil*/
var map_variable map[key_data_type]value_data_type

/* define the map as nil map can not be assigned any value*/
map_variable = make(map[key_data_type]value_data_type)

次の例は、マップを作成して使用する方法を示しています-

package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
  /* create a map*/
   countryCapitalMap = make(map[string]string)

  /* insert key-value pairs in the map*/
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"

  /* print map using keys*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

  /* test if entry is present in the map or not*/
   capital, ok := countryCapitalMap["United States"]

  /* if ok is true, entry is present otherwise entry is absent*/
   if(ok){
      fmt.Println("Capital of United States is", capital)
   } else {
      fmt.Println("Capital of United States is not present")
   }
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

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

delete()関数

delete()関数は、マップからエントリを削除するために使用されます。 マップと、削除する対応するキーが必要です。 たとえば-

package main

import "fmt"

func main() {
  /* create a map*/
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}

   fmt.Println("Original map")

  /*print map*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }

  /*delete an entry*/
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")

   fmt.Println("Updated map")

  /*print map*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}

上記のコードをコンパイルして実行すると、次の結果が生成されます-

Original 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
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo