A map is a data structure that provides you with an unordered collection of key/value pairs (maps are also sometimes called associative arrays in Php, hash tables in Java, or dictionaries in Python). Maps are used to look up a value by its associated key. You store values into the map based on a key.
The strength of a map is its ability to retrieve data quickly based on the key. A key works like an index, pointing to the value you associate with that key.
A map is implemented using a hash table, which is providing faster lookups on the data element and you can easily retrieve a value by providing the key. Maps are unordered collections, and there’s no way to predict the order in which the key/value pairs will be returned. Every iteration over a map could return a different order.
Go provides a built-in map type. In this article, we’ll learn how to use Golang’s built-in map type.
A Go map type looks like the following.
var m map[KeyType]ValueType
where KeyType may be any comparable type (more on this later), and ValueType may be any type at all, including another map.
See the variable m is a map of string keys to int values.
var m map[string]int
Map types are reference types, like pointers or slices, and so the value of m above is nil.
A nil map has no keys. A nil map behaves like a blank map when reading. Any attempt to add keys to a nil map will result in a runtime error.
See the below code of nil variable in Go.
// hello.go
package main
import "fmt"
func main() {
var app map[string]int
fmt.Println(app)
if app == nil {
fmt.Println("app variable is nil")
}
}
See the below output.
Now, let’s add the items to the nil map and see the output.
// hello.go
package main
import "fmt"
func main() {
var app map[string]int
app["dividend"] = 21
fmt.Println(app)
}
Output
It is, therefore, necessary to initialize a map before adding items to it.
You can initialize a map using the built-in make()
function. You just need to pass the type of the map to the make()
function as in the example below. The function will return an initialized and ready to use map -
// Initializing a map using the built-in make() function
var m = make(map[string]int)
Let’s see a complete example -
package main
import "fmt"
func main() {
var m = make(map[string]int)
fmt.Println(m)
if m == nil {
fmt.Println("m is nil")
} else {
fmt.Println("m is not nil")
}
// make() function returns an initialized and ready to use map.
// Since it is initialized, you can add new keys to it.
m["one hundred"] = 100
fmt.Println(m)
}
Output
map[]
m is not nil
map[one hundred:100]
A map literal is a very convenient way to initialize a map with some data. You just need to pass the key-value pairs separated by colon inside curly braces like this -
var m = map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
Note that the last trailing comma is necessary, otherwise, you’ll get a compiler error.
Let’s check out a complete example -
package main
import "fmt"
func main() {
var m = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5, // Comma is necessary
}
fmt.Println(m)
}
Output
map[one:1 two:2 three:3 four:4 five:5]
You can also create an empty map using a map literal by leaving the curly braces empty -
// Initialize an empty map
var m = map[string]int{}
The above statement is functionally identical to using the make()
function.
You can add new items to an initialized map using the following syntax -
m[key] = value
The following example initializes a map using the make() function and adds some new items to it -
package main
import "fmt"
func main() {
// Initializing a map
var tinderMatch = make(map[string]string)
// Adding keys to a map
tinderMatch["Rajeev"] = "Nano" // Assigns the value "Nano" to the key "Rajeev"
tinderMatch["Jack"] = "Sophia"
tinderMatch["David"] = "Tina"
fmt.Println(tinderMatch)
/*
Adding a key that already exists will simply override
the existing key with the new value
*/
tinderMatch["Rajeev"] = "Jony"
fmt.Println(tinderMatch)
}
Output
map[Rajeev:Nano Jack:Sophia David:Tina]
map[Rajeev:Jony Jack:Sophia David:Tina]
If you try to add a key that already exists in the map, then it will simply be overridden by the new value.
You can retrieve the value assigned to a key in a map using the syntax m[key]. If the key exists in the map, you’ll get the assigned value. Otherwise, you’ll get the zero value of the map’s value type.
Let’s check out an example to understand this -
package main
import "fmt"
func main() {
var personMobileNo = map[string]string{
"John": "+33-8273658526",
"Steve": "+1-8579822345",
"David": "+44-9462834443",
}
var mobileNo = personMobileNo["Steve"]
fmt.Println("Steve's Mobile No : ", mobileNo)
// If a key doesn't exist in the map, we get the zero value of the value type
mobileNo = personMobileNo["Jack"]
fmt.Println("Jack's Mobile No : ", mobileNo)
}
Output
Steve's Mobile No : +1-8579822345
Jack's Mobile No :
In the above example, since the key "Jack"
doesn’t exist in the map, we get the zero value of the map’s value type. Since the map’s value type is string
, we get " "
.
Unlike other languages, we do not get a runtime error in Golang if the key doesn’t exist in the map.
But what if you want to check for the existence of a key? In the above example, the map would return " "
even if the key "Jack"
existed with the value " "
. So how do we distinguish between cases where a key exists with the value equal to the zero value of the value type, and the absence of a key?
Well, let’s find out.
When you retrieve the value assigned to a given key using the syntax map[key]
, it returns an additional boolean value as well which is true
if the key exists in the map, and false
if it doesn’t exist.
So you can check for the existence of a key in a map by using the following two-value assignment
value, ok := m[key]
The boolean variable ok will be true
if the key exists, and false
otherwise.
Consider the following map for example. It maps employeeIds to names -
var employees = map[int]string{
1001: "Rajeev",
1002: "Sachin",
1003: "James",
}
Accessing the key 1001
will return "Rajeev"
and true, since the key 1001
exists in the map -
name, ok := employees[1001] // "Rajeev", true
However, If you try to access a key that doesn’t exist, then the map will return an empty string ""
(zero value of strings), and false
-
name, ok := employees[1010] // "", false
If you just want to check for the existence of a key without retrieving the value associated with that key, then you can use an _
(underscore) in place of the first value -
_, ok := employees[1005]
Now let’s check out a complete example
package main
import "fmt"
func main() {
var employees = map[int]string{
1001: "John",
1002: "Steve",
1003: "Maria",
}
printEmployee(employees, 1001)
printEmployee(employees, 1010)
if isEmployeeExists(employees, 1002) {
fmt.Println("EmployeeId 1002 found")
}
}
func printEmployee(employees map[int]string, employeeId int) {
if name, ok := employees[employeeId]; ok {
fmt.Printf("name = %s, ok = %v\n", name, ok)
} else {
fmt.Printf("EmployeeId %d not found\n", employeeId)
}
}
func isEmployeeExists(employees map[int]string, employeeId int) bool {
_, ok := employees[employeeId]
return ok
}
Output
name = Rajeev, ok = true
EmployeeId 1010 not found
EmployeeId 1002 found
In the above example, I’ve used a short declaration in the if
statement to initialize the name
and ok
values, and then test the boolean value ok
. It makes the code more concise.
You can delete a key from a map using the built-in delete()
function. The syntax looks like this -
// Delete the `key` from the `map`
delete(map, key)
The delete()
function doesn’t return any value. Also, it doesn’t do anything if the key doesn’t exist in the map.
Here is a complete example
package main
import "fmt"
func main() {
var fileExtensions = map[string]string{
"Python": ".py",
"C++": ".cpp",
"Java": ".java",
"Golang": ".go",
"Kotlin": ".kt",
}
fmt.Println(fileExtensions)
delete(fileExtensions, "Kotlin")
// delete function doesn't do anything if the key doesn't exist
delete(fileExtensions, "Javascript")
fmt.Println(fileExtensions)
}
Output
map[Python:.py C++:.cpp Java:.java Golang:.go Kotlin:.kt]
map[Python:.py C++:.cpp Java:.java Golang:.go]
Maps are reference types. When you assign a map to a new variable, they both refer to the same underlying data structure. Therefore changes done by one variable will be visible to the other -
package main
import "fmt"
func main() {
var m1 = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
}
var m2 = m1
fmt.Println("m1 = ", m1)
fmt.Println("m2 = ", m2)
m2["ten"] = 10
fmt.Println("\nm1 = ", m1)
fmt.Println("m2 = ", m2)
}
Output
m1 = map[one:1 two:2 three:3 four:4 five:5]
m2 = map[one:1 two:2 three:3 four:4 five:5]
m1 = map[one:1 two:2 three:3 four:4 five:5 ten:10]
m2 = map[one:1 two:2 three:3 four:4 five:5 ten:10]
The same concept applies when you pass a map to a function. Any changes done to the map inside the function is also visible to the caller.
You can iterate over a map using range
form of the for loop. It gives you the key
, value
pair in every iteration -
package main
import "fmt"
func main() {
var personAge = map[string]int{
"Rajeev": 25,
"James": 32,
"Sarah": 29,
}
for name, age := range personAge {
fmt.Println(name, age)
}
}
Output
James 32
Sarah 29
Rajeev 25
Note that, A map is an unordered collection and therefore the iteration order of a map is not guaranteed to be the same every time you iterate over it.
So if you run the above program multiple times, you’ll get the results in different orders.
The article ends here,Thanks for reading !
#go #golang