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() function
m := make(map[string]int)
In this example, m
is a map with string keys and int values. It’s an empty map at this point. The make()
function is used to create a map and allocate memory for it.
Alternatively, you can declare and initialize a map with some initial values:
// Initializing a map with values
m := map[string]int{"apple": 1, "orange": 2}
Example
package main
import "fmt"
func main() {
m := make(map[string]int) // creates an empty map
fmt.Println(m) // Output: map[]
}
Output
map[]
Here, the output shows an empty map
1. Adding Elements to a Map
You can add elements to a map by simply assigning a value to a specific key.
Syntax
m["key"] = value
Example
Add Element to the mapIn this case, two key-value pairs are added: "apple": 1
and "orange": 2
. When printed, the map displays both entries.
2. Accessing Elements in a Map
To access an element in a map, you use the key inside square brackets []
. If the key exists, it returns the corresponding value.
Syntax
value := m["key"]
Example
Access an elementHere, the value associated with the key "apple"
is retrieved, and the output is 1
.
3. Updating Values in a Map
Updating a map’s value is simple—just assign a new value to the existing key. This will overwrite the old value.
Syntax
m["key"] = newValue
Example
Updating mapIn this example, the value for the key "apple"
is updated from 1
to 10
.
4. Checking if a Key Exists in a Map
In Go, when you try to access an element in a map, it’s good practice to check whether the key exists. Go provides a two-value assignment when accessing a map: the value associated with the key and a boolean indicating whether the key is present.
Syntax
value, ok := m["key"]
value
holds the value associated with the key (or the zero value if the key is not present).ok
is a boolean (true
if the key exists, false
otherwise).
Example
package main
import "fmt"
func main() {
m := map[string]int{"apple": 1, "orange": 2}
val, ok := m["banana"]
if ok {
fmt.Println("Found:", val)
} else {
fmt.Println("Key not found")
}
}
Since "banana"
is not in the map, the output will be "Key not found"
.
5. Deleting Elements from a Map
To remove an element from a map, you can use the built-in delete()
function. This modifies the map in place and removes the specified key and its associated value.
Syntax
delete(m, "key")
Example
Deleting Elements from a MapAfter calling delete(m, "apple")
, the "apple"
key is removed from the map, and the output shows only the "orange"
key.
6. Passing Maps to Functions
Maps in Go are passed by reference, meaning that if you pass a map to a function, changes made inside the function will persist outside the function. This is a key feature of Go that allows for efficient data manipulation without having to return the modified map.
Example
package main
import "fmt"
func addChange(m map[string]int) {
m["apple"] = 50
}
func main() {
m := map[string]int{"apple": 1, "orange": 2}
addChange(m)
fmt.Println(m) // Output: map[apple:50 orange:2]
}
Here, the addChange()
function modifies the map m
directly, adding "apple": 50
. Since maps are passed by reference, no need to return the map for the changes to persist.
Conclusion
In Go, maps are mutable and provide an efficient way to manage key-value pairs. They allow adding, accessing, updating, and deleting elements dynamically. Understanding their mutable nature is crucial for handling dynamic data in applications like configurations, caches, and user data. Mastering maps helps in efficient data manipulation and real-time updates, making them a powerful tool for scalable development.
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
Composition in Golang Composition is a method employed to write re-usable segments of code. It is achieved when objects are made up of other smaller objects with particular behaviors, in other words, Larger objects with a wider functionality are embedded with smaller objects with specific behaviors. The end goal of compo
5 min read
Golang | Polymorphism Using Interfaces The word polymorphism means having many forms. Or in other words, we can define polymorphism as the ability of a message to be displayed in more than one form. Or in technical term polymorphism means same method name (but different signatures) being uses for different types. For example, a woman at
4 min read
Function Arguments in Golang In Golang, functions are groups of statements used to perform tasks, with optional returns. Go supports two main ways to pass arguments: Pass by Value and Pass by Reference. By default, Go uses pass-by-value.Basic Terms in Parameter Passing to Functions:Actual Parameters: The arguments passed to a f
2 min read
Golang program that uses structs as map keys A map in Golang is a collection of unordered pairs of key-value. It is widely used because it provides fast lookups and values that can retrieve, update or delete with the help of keys. Syntax: map[Key_Type]Value_Type{} Example: var sample map[string]int Here the sample is a map that has a string as
6 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