How to remove an item from a map in Go
In this shot, we will learn how to delete or remove an item from a map in Golang.
A map is an unordered collection of key-value pairs, where keys are unique.
We can remove an item from a map using the delete() function.
Syntax
delete(map, key)
Parameters
This function accepts map and key as parameters. It will delete the item for the given key in the given map.
Return value
It returns nothing, as this operation affects the original map.
Example
In this example, we will try to delete a fruit item from the map fruits, where the key is the fruit name and the value is the number of fruits.
Code
package main//import the format packageimport("fmt")//program execution starts herefunc main(){//declare and initialize a mapfruits := map[string]int{"orange":20,"apple":24,"guava":43,"watermelon":10,}//delete an itemdelete(fruits, "guava")//display the mapfmt.Println(fruits)}
Explanation
In the above code snippet:
- Line 5: We import the format package, which is useful for printing the map.
- Line 9: Program execution starts from
main()function in Golang. - Line 12: We declare and initialize the map
fruits, where keys are of thestringtype, and the values are of theinttype. - Line 20: We remove an item with the key
guavafrom the mapfruitsusing thedeletefunction. - Line 23: We display the map after deleting an item.