Lesson Description
Lession - #366 Go-Maps
Go - Maps
Go gives another significant information type named map which maps extraordinary keys to values. A key is an article that you use to recover a worth sometime in the future. Given a key and a worth, you can store the worth in a Map object. After the worth is put away, you can recover it by utilizing its key.
/* 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
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">
}
}
delete(>
Function
delete(>
function is utilized to erase a passage from a guide. It requires the guide and the comparing key which is to be erased. For instance −
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]>
}
}