Delete Key from a map in Go
A map is a data structure and an unordered collection of key-value pairs where keys are the unique identifiers.
Go provides a built-in method called delete()
to remove an element from the map.
Note: Even though we delete a key from the map, the delete()
function will delete its value as the key-value pair is a single entity when it comes to map in Golang.
Remove an item from map in Go
Let us look at removing an item from the map using the delete()
function with an example.
Syntax
The Syntax for delete()
function is:
delete(map,key)
Parameters
The delete()
function accepts two parameters:
map
: name of the mapkey
: the key of the element that needs to be deleted
Return Value
The delete()
function does not return anything as the delete happens in the original map.
Example: Delete an item from the map in golang
In our example, we have a list of cars where the car name is a key, and the quantity available is the value.
//Program to remove a key from the map
package main
import "fmt"
func main() {
// create a map
cars := map[string]int{
"Audi": 1250,
"Ford": 500,
"Volkswagen": 700,
"BMW": 400}
fmt.Println("Before Deletion:", cars)
// Delete an element using it's key
delete(cars, "Ford")
fmt.Println("After Deletion:", cars)
}
Output
Before Deletion: map[Audi:1250 BMW:400 Ford:500 Volkswagen:700]
After Deletion: map[Audi:1250 BMW:400 Volkswagen:700]
In the above Program -
- We have defined a map named
cars
, and the car name is the key and quantities as values inside the map. - We are removing an item with the key name
Ford
from thecars
map by passing the map name and key as an argument to the delete() function. - We display the map after deleting an item from the map.
Example 2: Remove a key from the map A better way to write a code that don't create a panic is to check if the key exists in the first place, as shown below.
// Program to remove a key from the map
package main
import "fmt"
func main() {
// create a map
cars := map[string]int{
"Audi": 1250,
"Ford": 500,
"Volkswagen": 700,
"BMW": 400}
fmt.Println("Before Deletion:", cars)
if _, ok := cars["ford"]; ok {
// Delete an element using it's key
delete(cars, "ford")
} else {
fmt.Println("Could not find the key in a map")
}
fmt.Println("After Deletion:", cars)
}
Output
Before Deletion: map[Audi:1250 BMW:400 Ford:500 Volkswagen:700]
Could not find the key in a map
After Deletion: map[Audi:1250 BMW:400 Ford:500 Volkswagen:700]
Note: The key name is case-sensitive when passing to the delete()
function.