WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Maps


Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date.

Defining a Map

/* 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)

Example

The following example illustrates how to create and use a map −
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["USA"] = "Washington D.C."
   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 kingdom"]
   
   /* if ok is true, entry is present otherwise entry is absent*/
   if(ok){
      fmt.Println("Capital of United kingdom is", capital)  
   } else {
      fmt.Println("Capital of United kingdom is not present") 
   }
}

Output

$go run main.go
Capital of USA is Washington D.C.
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Capital of United kingdom is not present