Golang program to get value from the hash collection based on specified key


In this golang article, we will write Go language programs to get the value from the hash collection based on a specified key using found variable as well as using ok idiom method.

A hash map is a data structure that belongs to the hash collection. It stores the data in the form of key value pairs.

Syntax

func make ([] type, size, capacity)

The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments.

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 hashmap using the make function which is a type of built-in function in Golang

  • Step 4 − Assign the value to the keys in the map

  • Step 5 − In this step, set the key whose value is to be obtained

  • Step 6 − Then, with the hep of found variable see the value is present in the map or not

  • Step 7 − If the found is true print the value of the key

  • Step 8 − If the found is false, this implies that no value is obtained for the key

  • Step 9 − The print statement is executed using the Printf function from the fmt package

Example 1

In this Example, we will create a hashmap using make function which a type of built-in function. Then, with the help of found variable value for the specified key will be obtained.

package main

import "fmt"

func main() {
	
   hashmap := make(map[string]string)

	
   hashmap["saree"] = "red"
   hashmap["kurti"] = "blue"
   hashmap["jacket"] = "green"

   key := "saree"

	
   value, found := hashmap[key]

   if found {
      fmt.Printf("The value for key '%s' is '%s'\n", key, value)
   } else {
      fmt.Printf("No value found for key '%s'\n", key)
   }
}

Output

The value for key 'saree' is 'red'

Example 2

In this illustration, we will create a hashmap and find the value from the map based on the key using ok idiom. ok returns either true or false.

package main

import "fmt"

func main() {
	
   hashmap := map[string]int{
      "pencils":   5,
      "pens":      10,
      "registers": 15,
   }
   key := "pens"

   value, ok := hashmap[key]

   if ok {
      fmt.Printf("The value for key '%s' is '%d'\n", key, value)
   } else {
      fmt.Printf("No value found for key '%s'\n", key)
   }
}

Output

The value for key 'pens' is '10'

Conclusion

We have successfully compiled and executed the program to get the value based on a specified key. In the first Example we used found variable to get the value based on a specified key and in the second Example we used ok idiom to perform the execution.

Updated on: 03-May-2023

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements