Go Map

Introduction

Go map is an unordered collection of key-value pairs.

Maps are used to look up a value by its associated key.

Here's an example of a map in Go:

var x map[string]int 

The map type is represented by the keyword map, followed by the key type in brackets and the value type.

To read this line, you would say "x is a map of strings to int values."

Like arrays and slices, maps can be accessed using brackets.

Try running the following program:

package main// w ww  .j av a2 s  .  c  o  m

import "fmt" 

func main(){
     var x map[string]int 
     x = make(map[string]int) 
     x["key"] = 10 
     fmt.Println(x["key"]) 

}

We can also create maps with a key type of int:

package main//ww w  .ja v  a2  s .  c  om

import "fmt" 

func main(){

     x := make(map[int]int) 
     x[1] = 10 
     fmt.Println(x[1]) 
}

We can also delete items from a map using the built-in delete function:

delete(x, 1) 

Let's look at an example program that uses a map:

package main//from  www .ja v  a2 s.c o  m

import "fmt" 

func main() { 
    elements  := make(map[string]string) 
    elements["H"] = "Hydrogen" 
    elements["He"] = "Helium" 
    elements["Li"] = "Lithium" 
    elements["Be"] = "Beryllium" 
    elements["B"] = "Boron" 
    elements["C"] = "Carbon" 
    elements["N"] = "Nitrogen" 
    elements["O"] = "Oxygen" 
    elements["F"] = "Fluorine" 
    elements["Ne"] = "Neon" 

    fmt.Println(elements["Li"]) 
} 

There is also a shorter way to create maps:

elements  := map[string]string{ /* w  w  w.  j  a  va  2s.co  m*/
         "H":  "Hydrogen", 
         "He": "Helium", 
         "Li": "Lithium", 
         "Be": "Beryllium", 
         "B":  "Boron", 
         "C":  "Carbon", 
         "N":  "Nitrogen", 
         "O":  "Oxygen", 
         "F":  "Fluorine", 
         "Ne": "Neon", 
} 



PreviousNext

Related