Open In App

Go - Mutating Maps

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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-elements-to-map
Add Element to the map

In 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-element
Access an element

Here, 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-a-map
Updating map

In 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

remove-an-element-from-map
Deleting Elements from a Map

After 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.


Article Tags :

Similar Reads