Home »
Golang »
Golang Programs
Golang program to delete an item from a map
Here, we are going to learn how to delete an item from a map in Golang (Go Language)?
Submitted by Nidhi, on March 24, 2021 [Last updated : March 04, 2023]
How to delete an item from a map in Golang?
Problem Solution:
In this program, we will create a simple map to store CountryCode using the make() function. Then we delete the specified item from the map using the delete() function. After that, we will store and print items of the map on the console screen.
Program/Source Code:
The source code to delete an item from a map is given below. The given program is compiled and executed successfully.
Golang code to delete an item from a map
// Golang program to delete an item from a map
package main
import "fmt"
func main() {
CountryCode := make(map[string]int)
CountryCode["ind"] = 101
CountryCode["aus"] = 102
CountryCode["eng"] = 103
CountryCode["pak"] = 104
CountryCode["usa"] = 105
delete(CountryCode, "pak")
fmt.Println("India :", CountryCode["ind"])
fmt.Println("Australia:", CountryCode["aus"])
fmt.Println("England :", CountryCode["eng"])
fmt.Println("Pakistan :", CountryCode["pak"])
fmt.Println("USA :", CountryCode["usa"])
}
Output:
India : 101
Australia: 102
England : 103
Pakistan : 0
USA : 105
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package to formatting related functions.
In the main() function, we created a CountryCode map using make() function to store country code of specified country. Map store items in KEY/VALUE pair. Then we removed "pak" from CountryCode map using delete() function. After that, we printed the items of the map on the console screen.
Golang Maps Programs »