Golang program to check a given key exists in the hash collection or not


In Golang we have inbuild function like ok idiom to check whether a given key exist in hash collection or not. Hashmap is a collection of values paired with key in hashmap collection. In this article, we will create a hashmap using the built-in function then we will use ok idiom that returns true false value to check whether a key exists in the map or not. In this way a success or failure statement will be printed.

Algorithm

  • Create a package main and declare fmt(format package) in the program where main produces executable codes and fmt helps in formatting input and output.

  • Create a main function and in the same function create a hashmap using map where keys are of type string and values are of type int.

  • Now, assign the key=item2 and using ok idiom and indexing check whether the particular key exists in the map or not.

  • If ok is true, print the success statement else print the failure statement.

  • In this step, we will repeat the step3 but this time with another key which doesn’t exist in the map i.e. item4.

  • We will use ok idiom to check if the key is present in the map or not, as ok will be false here so failure statement will be printed.

  • The output will be reflected on the console using Println function from fmt package where ln means new line.

Example

Golang program to check a given key exists in the hash collection or not using ok idiom function

package main
   
import "fmt"
   
//Main function to execute the program
func main() {
   
   // create a hash collection
   hashmap := map[string]string{
      "item1": "value1",
      "item2": "value2",
      "item3": "value3",
   }
   
   // check if a key exists in the hashmap
   key := "item2"
   if _, ok := hashmap[key]; ok {
      fmt.Printf("Item '%s' exists in the hash collection.\n", key)
   } else {
      fmt.Printf("item '%s' does not exist in the hash collection.\n", key)
   }
   
   // check if this key exists in the map or not (not found)
   key = "item4"
   if _, ok := hashmap[key]; ok {
      fmt.Printf("Item '%s' exists in the hash collection.\n", key)
   } else {
      fmt.Printf("Item'%s' does not exist in the hash collection.\n", key)
   }
}

Output

Item 'item2' exists in the hash collection.
Item'item4' does not exist in the hash collection.

Conclusion

We executed the program to check a given key exists in the hash collection or not using an example in which we used ok idiom to execute the program. The program executed successfully.

Updated on: 27-Mar-2023

76 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements