In Go (Golang), a map is a powerful and versatile data structure that acts as a collection of unordered key-value pairs. Maps are widely used due to their efficiency in providing fast lookups, updates, and deletions based on keys.
What is a Map?
A map in Go is essentially a reference to a hash table. This reference type is inexpensive to pass—taking up only 8 bytes on a 64-bit machine and 4 bytes on a 32-bit machine.
- Keys must be unique and of a comparable type, such as
int
, float64
, rune
, string
, arrays, structs, or pointers. However, types like slices and non-comparable arrays or structs cannot be used as keys. - Values, on the other hand, can be of any type, including another map, pointers, or even reference types.
Example
package main
import "fmt"
func main() {
// Creating and initializing a map with names and ages
ages := map[string]int{
"A": 30,
"B": 25,
"C": 35,
}
// Retrieving and printing B's age
fmt.Println("B's age:", ages["B"])
}
Syntax
map[Key_Type]Value_Type{} # Simple Initialization
make(map[Key_Type]Value_Type, initial_Capacity) # Using the make()
Function
make(map[Key_Type]Value_Type)
Maps Initialization
Maps must be initialized before use. There are two main methods for creating and initializing maps in Go:
Simple Initialization
You can create a map without using the make()
function by using the following syntax:
Syntax
# An empty map
map[Key_Type]Value_Type{}
# Map with key-value pairs
map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}
Example:
Go
package main
import "fmt"
func main() {
// Creating and initializing a map with names and ages
ages := map[string]int{
"A": 30,
"B": 25,
"C": 35,
}
// Retrieving and printing B's age
fmt.Println("B's age:", ages["B"])
}
Using the make()
Function
Another way to create a map is by using the built-in make()
function.
Syntax
make(map[Key_Type]Value_Type, initial_Capacity)
make(map[Key_Type]Value_Type)
Example:
Go
package main
import "fmt"
func main() {
// Creating a map using the make function
ages := make(map[string]int)
// Initializing the map with names and ages
ages["A"] = 30
ages["B"] = 25
ages["C"] = 35
// Retrieving and printing B's age
fmt.Println("B's age:", ages["B"])
}
Important Operations with Maps
Iterating Over a Map
You can iterate through a map using the for range
loop. Since maps are unordered, the order of iteration may vary.
Example:
for key, value := range myMap {
fmt.Println(key, value)
}
Adding Key-Value Pairs
You can add key-value pairs to an initialized map using the following syntax:
Syntax
myMap[key] = value
If the key already exists, its value will be overwritten.
Example:
myMap[3] = "Three" // Adds a new entry
myMap[1] = "Updated One" // Updates existing entry
Retrieving Values
You can retrieve a value from a map using its key:
value := myMap[key]
If the key does not exist, it will return the zero value for the map’s value type.
Checking Key Existence
To check if a key exists in a map, you can use the following syntax:
Syntax
value, exists := myMap[key]
If exists
is true
, the key is present; if false
, it is not.
Example:
if pet, ok := myMap[2]; ok {
fmt.Println("Key exists:", pet)
} else {
fmt.Println("Key does not exist")
}
Deleting a Key
You can delete a key from a map using the built-in delete()
function:
Syntax
delete(myMap, key)
Example:
delete(myMap, 1) // Removes the key 1 from the map
Modifying Maps
Since maps are reference types, assigning one map to another variable will not create a copy but will instead reference the same underlying data structure. Thus, modifications to one map will affect the other.
Similar Reads
Golang Maps
In Go (Golang), a map is a powerful and versatile data structure that acts as a collection of unordered key-value pairs. Maps are widely used due to their efficiency in providing fast lookups, updates, and deletions based on keys. What is a Map?A map in Go is essentially a reference to a hash table.
3 min read
Comparing Maps in Golang
In Go, a map is a powerful and versatile data structure that consists of unordered key-value pairs. It offers fast lookups and allows for efficient updates and deletions based on keys. To compare two maps in Go, you can use the DeepEqual() function provided by the reflect package. This function chec
3 min read
Slices in Golang
Slices in Go are a flexible and efficient way to represent arrays, and they are often used in place of arrays because of their dynamic size and added features. A slice is a reference to a portion of an array. It's a data structure that describes a portion of an array by specifying the starting index
14 min read
Nested loops in golang
Nested loops in Go are loops placed within other loops. This structure allows you to iterate over multiple data structures or perform complex operations that require multiple levels of iteration. With each iteration of the outer loop, the inner loop runs from start to finish. Nested loops are common
4 min read
Go - Mutating Maps
To start using maps in Go, we need to define them first. Maps in Go are declared using either the make() function or by initializing them directly. A map consists of key-value pairs where: Keys are unique.Values can be of any type (int, string, struct, etc.).Syntax // Using make() functionm := make(
4 min read
Zero value in Golang
In Go language, whenever we allocate memory for a variable with the help of declaration or by using new and if the variable is not initialized explicitly, then the value of such types of variables are automatically initialized with their zero value. The initialization of the zero value is done recur
3 min read
Channel in Golang
In Go language, a channel is a medium through which a goroutine communicates with another goroutine and this communication is lock-free. Or in other words, a channel is a technique which allows to let one goroutine to send data to another goroutine. By default channel is bidirectional, means the gor
7 min read
How to Install Golang on MacOS?
Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but
4 min read
Generics in Golang
Generics are essentially template/boilerplate code written in a form to use on the Go with types that can be added later. The main aim of generics is to achieve greater flexibility in terms of writing code with the addition of fewer lines. The concept of Generics has existed for a long time now and
4 min read
How to Parse JSON in Golang?
Golang provides multiple APIs to work with JSON including to and from built-in and custom data types using the encoding/json package. To parse JSON, we use the Unmarshal() function in package encoding/json to unpack or decode the data from JSON to a struct. Syntax: func Unmarshal(data []byte, v inte
4 min read