Maps in Go
In Go lang, a map is a data structure that stores key-value pairs where keys must be unique but values can be duplicate.
Maps provide easy retrieval of values. It is a reference to an underlying hash table.
Declare Maps
Maps can be declared using var or shorthand syntax.
// Using var keyword
var mymap = map[TypeOfKey] TypeOfValue { key1:value1, key2:value2,...}
// shorthand syntax
mymap := map[TypeOfKey] TypeOfValue { key1:value1, key2:value2,...}
The following example declares maps using var keyword and := syntax:
package main
import "fmt"
func main() {
//using var
var emplist = map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
fmt.Println(emplist)
//shorthand syntax
empsal := map[string] int {"Steve":60000, "Roy":70000, "Amar":75000, "Nancy":60000, "Abdul":65000}
fmt.Println(empsal)
}
[1:Steve 2:Roy 3:Amar 4:Nancy 5:Abdul]
map[Abdul:65000 Amar:75000 Nancy:60000 Roy:70000 Steve:60000]
In the above example, a map named emplist
is created using the var
keyword with int type keys and string type values.
Keys stores employee ids and the values store names.
The map empsal
is created using shorthand syntax :=
with keys of string type and value of type int.
Sometimes the order of declaration of the key-value pairs is different from the order in which they are stored.
In the above example, the order of the key-value pairs in the output of empsal
is different from the declared order.
This is because the data in a map is stored efficiently to make retrieval easier.
Create Map using make() Function
The built-in make()
function can be used to create an empty map by specifying the key and value type, as shown below.
// create an empty map
var emplist = make(map[int]string)
fmt.Println(emplist) //output: map[]
// Add members to the map
emplist[1] = "Steve"
emplist[2] = "Roy"
emplist[3] = "Amar"
emplist[4] = "Nancy"
emplist[5] = "Abdul"
fmt.Println(emplist) //output: [1:Steve 2:Roy 3:Amar 4:Nancy 5:Abdul]
Valid Types for Map
The data type of a key element should be a type that can be compared using the == operator.
Valid Key Types: Numbers, string, Boolean, arrays, pointers, struct
Invalid Key Types: functions, slices, and maps
The type of value can be of any type.
Access Maps
The values in a map can be retrieved by passing the key in the square bracket, e.g. map[key]
.
The following retrieves the map values.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
fmt.Println(emplist[1]) // output: Steve
fmt.Println(emplist[2]) // output: Roy
fmt.Println(emplist[3]) // output: Amar
fmt.Println(emplist[4]) // output: Nancy
fmt.Println(emplist[5]) // output: Abdul
fmt.Println(emplist[15]) // output:
Check If Key Exists
The map[key]
returns two values, first the value itself, and second, true or false depending upon if the specified key exists or not. It returns true if a key exists; otherwise returns false.
If the specified key does not exist then the value will be the default value of the type of value.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
//check for an existing key
val, ok := emplist[3]
fmt.Println(val, ok) //output: Amar true
//check for a non-existing key
val2, ok := emplist[7]
fmt.Println(val2, ok)
In the above example, key 3 exists in the emplist
map and so it returns the value associated with key 3 and returns true
.
For key value 7, it returns the default value of string which is a blank string "", and also returns false
because key 7 does not exist.
Add or Update Elements
You can add a new element or update an existing one in the map using the map[key]
.
The following updates the value of an existing key 2, and adds a new key 6, and its value to the map.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
emplist[2] = "Yash" //update
emplist[6] = "Anita" //add
fmt.Println(emplist) //output:map[1:Steve 2:Yash 3:Amar 4:Nancy 5:Abdul 6:Anita]
Delete Map Element
Use the delete(map, key)
function to remove a key value pair from a map.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
delete(emplist, 1)
delete(emplist, 2)
fmt.Println(emplist) //output: map[3:Amar 4:Nancy 5:Abdul 6:Anita]
Get Count of Map Elements
The len()
function returns the total number of elements in a map.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
fmt.Println(len(emplist)) //output: 5
Iterating Map using for Loop
Similar to arrays, you can iterate through a map using the for loop.
emplist := map[int] string {1:"Steve", 2:"Roy", 3:"Amar", 4:"Nancy", 5:"Abdul" }
for keyVar, val := range emplist {
fmt.Printf("%v : %v, ", keyVar, val) // output 3 : Amar, 4 : Nancy, 5 : Abdul, 1 : Steve, 2 : Roy,
}