Friday, 3 May 2019

Go Language: Map: Check whether an item exists in map or not


By using double value context, we can check whether an item exists in the map or not.

value1, ok := employees[1]
if !ok {
         fmt.Println("Value not found for key 1")
} else {
         fmt.Println("Value for key 1 : ", value1)
}

ok value will be assigned to true, if the key is inside the map, else false.
value1 is assigned with the value of key 1, if key 1 exists in the map else assigned with zero value.

App.go
package main

import "fmt"

func main() {

 employees := map[int]string{
  1: "Krishna",
  2: "Ram", //Must have trailing comma
 }

 value1, ok := employees[1]
 if !ok {
  fmt.Println("Value not found for key 1")
 } else {
  fmt.Println("Value for key 1 : ", value1)
 }

 value2, ok := employees[10]
 if !ok {
  fmt.Println("Value not found for key 10")
 } else {
  fmt.Println("Value for key 10 : ", value2)
 }
}

Output
Value for key 1 :  Krishna
Value not found for key 10



Previous                                                 Next                                                 Home

No comments:

Post a Comment