exists Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/exists/ Tue, 09 Jun 2020 09:03:58 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 exists Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/exists/ 32 32 159787465 An efficient way to check if a key exists in a Map in Go (Golang) https://vikasboss.github.io/check-key-exists-map-golang/ https://vikasboss.github.io/check-key-exists-map-golang/#respond Tue, 09 Jun 2020 09:03:46 +0000 https://vikasboss.github.io/?p=2216 Below is the format to check if a key exist in the map There are two cases If the key exists val variable be the value of the key in the map...

The post An efficient way to check if a key exists in a Map in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Below is the format to check if a key exist in the map

val, ok := mapName[key]

There are two cases

  • If the key exists val variable be the value of the key in the map and ok variable will be true
  • If the key doesn’t exist val variable will be default zero value of value type and ok variable will be false

Let’s see an example

package main

import "fmt"

func main() {
    //Declare
    employeeSalary := make(map[string]int)

    //Adding a key value
    employeeSalary["Tom"] = 2000
    fmt.Println("Key exists case")
    val, ok := employeeSalary["Tom"]
    fmt.Printf("Val: %d, ok: %t\n", val, ok)
    fmt.Println("Key doesn't exists case")

    val, ok = employeeSalary["Sam"]
    fmt.Printf("Val: %d, ok: %t\n", val, ok)
}

Output

Key exists case
Val: 2000, ok: true
Key doesn't exists case
Val: 0, ok: false

In above program when key exists then val variable is set to the actual value which is 2000 hereĀ  and ok variable is true. When key doesn’t exist the val variable is set to 0 which is default zero value of int and ok variable is false. This ok variable is the best way to check if the key exists in a map or not

In case we only want to check if a key is present and val is not needed, then blank identifier i.e “_” can be used in place of val.

_, ok = employeeSalary["Sam"]

The post An efficient way to check if a key exists in a Map in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/check-key-exists-map-golang/feed/ 0 2216