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
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOSÂ Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protect
9 min read
Templates in GoLang
Template in Golang is a robust feature to create dynamic content or show customized output to the user. Golang has two packages with templates: text/template html/template There are mainly 3 parts of a template which are as follows: 1. Actions They are data evaluations, control structures like loops
4 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
Packages in Golang
Packages are the most powerful part of the Go language. The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easy to maintain and understand and independent of the other package programs. This modula
5 min read
math Package in Golang
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. FunctionDescriptionAbsThis function is used to return the absolute value of the specified number.AcosThis function returns the arccosine, in ra
7 min read
Polymorphism in GoLang
Polymorphism is the ability of a message to be displayed in more than one form. Polymorphism is considered one of the important features of Object-Oriented Programming and can be achieved during either runtime or compile time. Golang is a light-object-oriented language and supports polymorphism thro
4 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
Interfaces in Golang
In Go, an interface is a type that lists methods without providing their code. You canât create an instance of an interface directly, but you can make a variable of the interface type to store any value that has the needed methods.Exampletype Shape interface { Area() float64 Perimeter() float64}In t
3 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
3 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(ma
3 min read