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 package
import(
"fmt"
)
//program execution starts here
func main(){
//declare and initialize a map
fruits := map[string]int{
"orange":20,
"apple":24,
"guava":43,
"watermelon":10,
}
//delete an item
delete(fruits, "guava")
//display the map
fmt.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 the string type, and the values are of the int type.
  • Line 20: We remove an item with the key guava from the map fruits using the delete function.
  • Line 23: We display the map after deleting an item.

Free Resources