0
0
Goprogramming~5 mins

Deleting map entries in Go

Choose your learning style9 modes available
Introduction
Deleting map entries helps you remove data you no longer need, keeping your program clean and efficient.
When you want to remove a user from a list after they log out.
When you need to clear outdated cache data from a map.
When you want to delete a product from an inventory map after it is sold out.
When you want to remove temporary settings after a task is done.
Syntax
Go
package main

import "fmt"

func main() {
    myMap := map[string]int{"apple": 5, "banana": 3}
    delete(myMap, "apple")
    fmt.Println(myMap)
}
Use the built-in delete() function with two arguments: the map and the key to remove.
If the key does not exist, delete() does nothing and does not cause an error.
Examples
Deleting a key from an empty map does nothing and does not cause an error.
Go
package main

import "fmt"

func main() {
    myMap := map[string]int{}
    delete(myMap, "nonexistent")
    fmt.Println(myMap)
}
Deleting the only key in the map results in an empty map.
Go
package main

import "fmt"

func main() {
    myMap := map[string]int{"onlyKey": 10}
    delete(myMap, "onlyKey")
    fmt.Println(myMap)
}
Deleting a key at the beginning of the map removes that entry.
Go
package main

import "fmt"

func main() {
    myMap := map[string]int{"first": 1, "second": 2, "third": 3}
    delete(myMap, "first")
    fmt.Println(myMap)
}
Deleting a key at the end of the map removes that entry.
Go
package main

import "fmt"

func main() {
    myMap := map[string]int{"first": 1, "second": 2, "third": 3}
    delete(myMap, "third")
    fmt.Println(myMap)
}
Sample Program
This program shows how to delete a key from a map and what happens if you try to delete a key that is not there.
Go
package main

import "fmt"

func main() {
    // Create a map with some fruit counts
    fruitCounts := map[string]int{"apple": 10, "banana": 5, "cherry": 7}

    fmt.Println("Before deletion:")
    fmt.Println(fruitCounts)

    // Delete the entry for "banana"
    delete(fruitCounts, "banana")

    fmt.Println("After deletion of 'banana':")
    fmt.Println(fruitCounts)

    // Try deleting a key that does not exist
    delete(fruitCounts, "orange")

    fmt.Println("After attempting to delete non-existent 'orange':")
    fmt.Println(fruitCounts)
}
OutputSuccess
Important Notes
Time complexity of delete operation is O(1) on average.
Space complexity is O(1) since no extra space is needed to delete an entry.
A common mistake is trying to delete a key from a nil map, which causes a runtime panic.
Use delete when you want to remove specific entries; to clear all entries, create a new map instead.
Summary
Use the built-in delete(map, key) function to remove entries from a map.
Deleting a non-existent key does nothing and is safe.
Deleting from a nil map causes a runtime error, so ensure the map is initialized.