In this tutorial, we will be checking out the Go Map data type which falls under the reference data type of composite type. You will learn what a map means in Golang, how it is defined, declared & initialized, and will also discuss some of the operations to be used with the map.
A map is a data structure that contains a set of key-value pairs. In maps, key-value pairs are an unordered collection or combination of data that needs to be stored like a dictionary or hash table or like an associative array.
Note: keys are unique, values may vary in Map
In Golang, Map is the keyword & the name given to the data structure. The syntax to define a map in Golang starts with the map
keyword followed by mentioning the datatype of a key in square bracket “[ ]” & the data type of values. The key-value pairs are initialized within the curly braces.
The General syntax used to declare maps in Golang is
map [key_<datatype>] value_<datatype>{}
For example:
Var a = make(map[string]int{
“first” : 1
“second”: 2
}
a := make(map[string]int){
“first” : 1
“second”: 2
}
map
data structure which is further created using the make function
.make( )
concept is similar to what we discussed in the slice tutorial which will be discussed in detail in the next section of this tutorial.In Golang maps are created and initialized in the following ways:
make( )
creates an empty map if curly brackets are not provided with specific key-value pairs to initialize them. Let us see how to make an empty map using make( )
.
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs with nil values
//creates an empty map
Tutorial = make(map[string]string)
fmt.Println( Tutorial)
}
Output:
map[]
In the given example a variable Tutorial
is declared of map type. The map type specifies both key–values of string types.
var Tutorial map[string]string
In order to create a map we use the make function, here in this example no key values are specified inside curly braces so returns an empty map.
//initialize the key-value pairs with nil values
//creates an empty map
Tutorial = make(map[string]string)
Now we are going to check how to initialize values in the same code explained above after making the function creates a map. Let us again understand with the same example with some more simple codes added to it.
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Println( Tutorial)
fmt.Printf("%q\n", Tutorial)
}
Output:
map[ Tutorial:Learn eTutorials Go:LANG] map[" Tutorial":"Learn eTutorials" "Go":"LANG"]
Till the creation of empty map using make function is same as above codes.
Tutorial = make (map[string]string)
Tutorial["Go"] = "LANG" //line1
Tutorial[" Tutorial"] = "Learn eTutorials" //line2
The key value is initialized in line1 & line 2. Calls the variable name with a square bracket specifies the type of key followed by an assignment operator to assign value to the key.
In this example, line1 assigns the key “Go” of string type with the value “LANG” of string type.
Using literal notation you can create & initialize a map in Golang, The below codes show how to represent literal notation :
// creating a map of string & float32 type
s := map[string]float32{
"pi": 3.14159, /* initializing key-value pairs */
"First": 1,
"Second": 2,
}
In the above code, s is created of map type with key-value pairs specified as a string and float32 type using a shorthand notation. Inside the curly braces, we specify the values associated with each key by assigning them using a “:”( colon). Each key-value pair is separated by a comma.
Let us understand with an example that shows the output as shown below:
package main
import "fmt"
func main() {
// creating a map of string & float32 type
s := map[string]float32{
"pi": 3.14159, /* initializing key-value pairs */
"First": 1,
"Second": 2,
}
fmt.Println(s) //dispalys output
}
Output:
map[First:1 Second:2 pi:3.14159]]
Note: The difference we need to note in both types of initialization is shorthand or literal notation uses curly braces {}to specify the key-value pairs whereas in the case of make ( ), no such concept.
The length function is denoted by len( )
represents the number of key-value pairs initialized inside curly braces when a map is created.
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Printf("%q\n", Tutorial)
//len() displays no of key-value pairs
fmt.Printf("There are %d pairs in the map\n", len(Tutorial))
}
Output:
map[" Tutorial":"Learn eTutorials" "Go":"LANG"] There are 2 pairs in the map
In the above code number of pairs is 2 ie
"Tutorial":"Learn eTutorials" (first key-value pair)
"Go":"LANG" (second key-value pair)
In Golang map elements are iterated using for & range loops.
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Printf("%q\n", Tutorial)
fmt.Println(".................................")
fmt.Println("Two Different representation using for & range")
//for & range loop
for key, value := range Tutorial {
fmt.Printf("Tutorial[%s] = %s\n", key, value)
}
fmt.Println("")
for LEARN := range Tutorial {
fmt.Println(LEARN, "=>", Tutorial[LEARN])
}
fmt.Println("")
}
Output:
map[" Tutorial":"Learn eTutorials" "Go":"LANG"] ................................. Two Different representation using for & range Tutorial[Go] = LANG Tutorial[ Tutorial] = Learn eTutorials Go => LANG Tutorial => Learn eTutorials
for key, value := range Tutorial {
fmt.Printf("Tutorial[%s] = %s\n", key, value)
}
The syntax or code using for and range keywords iterate as pair objects to provide output
Tutorial[Go] = LANG
Tutorial[ Tutorial] = Learn eTutorials
for LEARN := range Tutorial {
fmt.Println(LEARN, "=>", Tutorial[LEARN])
}
The syntax or code using for and range keywords iterate as key-value pairs to provide output
Go => LANG
Tutorial => Learn eTutorials
Map operations in Golang include insert, delete, update, and retrieve. Let us check in detail each operation.
Delete keyword followed by name of map and element to eliminate by specifying its key performs deletion operation in map.
Example
delete(s,"pi")
This syntax deletes pi from map s created. Look at the below program & output for better understanding.
package main
import "fmt"
func main() {
// creating a map of string & float32 type
s := map[string]float32{
"pi": 3.14159, /* initializing key-value pairs */
"First": 1,
"Second": 2,
}
fmt.Println(s) //dispalys output
delete(s,"pi")
fmt.Println(s)
}
Output:
map[First:1 Second:2 pi:3.14159] map[First:1 Second:2]
In Golang, new key-value pairs can be inserted whenever is needed. Likewise, we can update the already specified value. For example, in below program created tutorial map
Which contains the following two key-value pairs as shown in the output.
“Tutorial”: “Learn eTutorials"
"Go”: “LANG"
Later inserted a new key-value pair using syntax now length will change to three
Tutorial ["Insert"] = "new string"
with output as
“Tutorial”: “Learn eTutorials"
"Go”: “LANG"
"Insert”: “new string"
Note: Update operation is almost similar to insert the only difference is we specify a new value to already defined key type, which replaces the old value.
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
fmt.Println( Tutorial)
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Printf("%q\n", Tutorial)
//insert operation
Tutorial["Insert"] = "new string"
fmt.Printf("%q\n", Tutorial)
//update operation
Tutorial["Tutorial"] = "Learn eTutorials users"
fmt.Printf("Updated %q\n", Tutorial)
}
Output:
map[] map[" Tutorial":"Learn eTutorials" "Go":"LANG"] map[" Tutorial":"Learn eTutorials" "Go":"LANG" "Insert":"new string"] Updated map[" Tutorial":"Learn eTutorials" "Go":"LANG" "Insert":"new string" "Tutorial":"Learn eTutorials users"]
In Golang retrieve operations allows to get back a value assigned to a specific key from an already existing or created map. The operation retrieves the values if and only if such a key-value pair exist else it returns a zero value.
The syntax to be used to retrieve a value is give below
map_Name[key]
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
fmt.Println(Tutorial) // displays an empty map
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Printf("%q\n", Tutorial) // displays non empy map
//retrieve operation using var keyword
var LangName = Tutorial["Go"]
fmt.Println("Name of Language is %q : ", LangName)
//retrieve operation in single statement
fmt.Println("SiteName is %q :", Tutorial[" Tutorial"])
//retrieve operation returns an empty string " " if no key-pair exist
fmt.Println("Retrieve operation returns an empty string :", Tutorial[" year"])
}
Output:
map[] map[" Tutorial":"Learn eTutorials" "Go":"LANG"] Name of Language is %q : LANG SiteName is %q : Learn eTutorials Retrieve operation returns an empty string : Program exited.
Note: if map does not exist return a zero value based on the type of map.
In the above example map created is of type string so return blank space which denotes empty string in case of integer value returns with 0 as in below given program
package main
import "fmt"
func main() {
// Declare a variable tutorial of type map
var Tutorial map[string]string
//initialize the key-value pairs
Tutorial = make(map[string]string)
fmt.Println(Tutorial) // displays an empty map
Tutorial["Go"] = "LANG"
Tutorial[" Tutorial"] = "Learn eTutorials"
fmt.Printf("%q\n", Tutorial) // displays non empy map
//retrieve operation using var keyword
var LangName = Tutorial["Go"]
fmt.Println("Name of Language is %q : ", LangName)
//retrieve operation in single statement
fmt.Println("SiteName is %q :", Tutorial[" Tutorial"])
//retrieve operation returns an empty string " " if no key-pair exist
fmt.Println("Retrieve operation returns an empty string :", Tutorial[" year"])
}
Output:
map[] map[" Tutorial":"Learn eTutorials" "Go":"LANG"] Name of Language is %q : LANG SiteName is %q : Learn eTutorials Retrieve operation returns an empty string : Program exited.
package main
import "fmt"
func main() {
var m = map[string]int{
"one": 1,
"two": 2,
"three": 3,
// Comma is necessary
}
fmt.Println(m)
fmt.Println(m["six"]) //retrieve a 0 value for non existing key-value pair for map of int type
}
Output:
map[one:1 three:3 two:2] 0 Program exited.