Maps in Go

Discover how to use maps in Go to store key-value pairs. Learn about creating, accessing, and modifying map elements.


Modifying Maps in Go

Maps in Go are dynamic data structures that allow you to store and retrieve values using keys. They are incredibly versatile and commonly used. Understanding how to modify maps – adding, updating, and deleting entries – is crucial for working with them effectively.

Adding New Key-Value Pairs

Adding a new key-value pair to a map is straightforward. You simply assign a value to a non-existent key using the assignment operator (=).

 package main

  import "fmt"

  func main() {
    myMap := map[string]int{
      "apple": 1,
      "banana": 2,
    }

    fmt.Println("Original map:", myMap) // Output: Original map: map[apple:1 banana:2]

    // Add a new key-value pair
    myMap["orange"] = 3

    fmt.Println("Map after adding 'orange':", myMap) // Output: Map after adding 'orange': map[apple:1 banana:2 orange:3]
  } 

In this example, myMap["orange"] = 3 adds a new key-value pair where the key is "orange" and the value is 3. If the key "orange" already existed, the value would be overwritten (as explained in the next section).

Updating Existing Values

Updating the value associated with an existing key is equally simple. You use the same assignment operator (=) as when adding a new entry, but with a key that already exists in the map.

 package main

  import "fmt"

  func main() {
    myMap := map[string]int{
      "apple": 1,
      "banana": 2,
    }

    fmt.Println("Original map:", myMap) // Output: Original map: map[apple:1 banana:2]

    // Update the value associated with the key "apple"
    myMap["apple"] = 10

    fmt.Println("Map after updating 'apple':", myMap) // Output: Map after updating 'apple': map[apple:10 banana:2]
  } 

Here, myMap["apple"] = 10 changes the value associated with the key "apple" from 1 to 10.

Deleting Entries from a Map

To delete an entry from a map, you use the delete() function. This function takes the map and the key you want to delete as arguments.

 package main

  import "fmt"

  func main() {
    myMap := map[string]int{
      "apple": 1,
      "banana": 2,
      "orange": 3,
    }

    fmt.Println("Original map:", myMap) // Output: Original map: map[apple:1 banana:2 orange:3]

    // Delete the entry with the key "banana"
    delete(myMap, "banana")

    fmt.Println("Map after deleting 'banana':", myMap) // Output: Map after deleting 'banana': map[apple:1 orange:3]
  } 

The delete(myMap, "banana") statement removes the key-value pair associated with the key "banana" from the map. If the key doesn't exist, the delete() function does nothing, and no error is raised.