remove a key-value pair from a map in go

To remove a specific key-value pair from a map in Golang, we need to use the built-in delete function. The delete function takes two arguments: the map and the key. Here's an example:

main.go
package main

import "fmt"

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

    // print the map before deleting a key-value pair
    fmt.Println("Before:", myMap)

    // delete the "banana" key-value pair
    delete(myMap, "banana")

    // print the map after deleting a key-value pair
    fmt.Println("After:", myMap)
}
409 chars
22 lines

Output:

main.go
Before: map[apple:2 banana:3 orange:4]
After: map[apple:2 orange:4]
68 chars
3 lines

In this example, we define a map named myMap with three key-value pairs. We then print the map before deleting a key-value pair, delete the "banana" key-value pair using the delete function, and then print the map again to confirm that the "banana" key-value pair has been removed.

gistlibby LogSnag