
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Item from Hash Collection in Go
In this article, we will learn how tp write a Go language programs to delete the item from the hash collection based on a specified key using ok idiom method and delete keyword
A hash map is a part of the hash collection. It stores the data as key value pairs which helps in the efficient execution of the program.
Algorithm
Step 1 ? This program imports two packages fmt and main where fmt helps in the formatting of input and output and main helps in generating executable codes
Step 2 ? Create a main function
Step 3 ? In the main, create a hash map using map literal with keys of type string and values of type int
Step 4 ? Set the values of the keys in the map
Step 5 ? In this step, print the map on the console
Step 6 ? Then, use ok idiom and delete keyword to delete the specific key from the hashmap
Step 7 ? Then, print the updated map on the console
Step 8 ? The print statement is executed using Println function from the fmt package where ln means new line
Example 1
In this Example, we will create a main function and, in that function, we will create a hash map using map literal where keys are of type string and values are of type int. Use ok idiom to delete the key from the map.
package main import "fmt" func main() { hashmap := map[string]int{ "pen": 10, "pencil": 20, "scale": 30, } fmt.Println("Original map:", hashmap) if _, ok := hashmap["pen"]; ok { delete(hashmap, "pen") } fmt.Println("Updated map:", hashmap) }
Output
Original map: map[pen:10 pencil:20 scale:30] Updated map: map[pencil:20 scale:30]
Example 2
In this Example, we will create a hashmap using map literal. Then, we will use delete keyword with two inputs the map and the key which is to be deleted.
package main import "fmt" func main() { hashmap := map[string]int{ "pen": 10, "pencil": 20, "scale": 30, } fmt.Println("Original map:", hashmap) delete(hashmap, "pen") fmt.Println("Updated map:", hashmap) }
Output
Original map: map[pen:10 pencil:20 scale:30] Updated map: map[pencil:20 scale:30]
Conclusion
We executed the program of deleting the item from the hashmap based on a specific key. In the first Example we used ok idiom to delete the item from the map and in the second Example we will use the delete keyword in a simple way.