Friday, 10 May 2019

Go: Map: Check for the existence of key in Go


Below snippet is used to check for the existence of key in a map.

if value, ok := map[key]; ok {
    //If key exists in the map, then this code will get executed
} else {
    //If key not exists in the map, then this code will get executed
}

If ‘key’ exists in the map, then the variable ‘ok’ is set to true, and value associated with key is assigned to ‘value’.

If ‘key’ is not exists in the map, then the variable ‘ok’ is set to false, and value is set to ‘zero’ value.

App.go
package main

import "fmt"

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

    employees[1] = "Krishna"
    employees[2] = "Chamu"
    employees[123] = "Ram"

    key1 := 123

    if value, ok := employees[key1]; ok {
        fmt.Printf("Employee name for the id %v is %v \n", key1, value)
    } else {
        fmt.Printf("Employee with id %v is not exist\n", key1)
    }

    key2 := 125

    if value, ok := employees[key2]; ok {
        fmt.Printf("Employee name for the id %v is %v \n", key2, value)
    } else {
        fmt.Printf("Employee with id %v is not exist\n", key2)
    }
}

Output
Employee name for the id 123 is Ram
Employee with id 125 is not exist


Previous                                                 Next                                                 Home

No comments:

Post a Comment