How to check if key exists in a map in Golang?

Here, we are going to learn how to check whether a key exists in a map or not in Golang?
Submitted by Anshuman Singh, on July 21, 2019 [Last updated : March 05, 2023]

Checking if key exists in a map

When you try to get the value of key in a map, you get two return values. The first value is the value of key and second is bool value which could be either true or false. If a key is present in the map then the second value will be true else false.

If a key is not present in the map then the first value will be default zero value.

Syntax

first_value, second_value := map_variable_name[key_name]
    or
first_value := map_variable_name[key_name]
    or
first_value, _ := map_variable_name[key_name]

Here, second_value is optional.

Golang code to check if whether a key exists in a map or not

package main

import (
    "fmt"
)

func main() {
  m:= map[string]int{"apple": 1}

  value, ok := m["apple"]
  fmt.Println(value, ok)

  value, ok = m["mango"]
  fmt.Println(value, ok)
}

Output

1 true
0 false

Golang code to check if whether a key exists in a map or not using if-statement

package main

import (
    "fmt"
)

func main() {
  m:= map[string]int{"apple": 1}

  if value, ok := m["apple"]; ok {
    fmt.Printf("Apple is present in map. Value is: %d\n", value)
  } else {
    fmt.Printf("Apple is not present in map. Value is: %d\n", value)
  }

  if value, ok := m["mango"]; ok {
    fmt.Printf("Mango is present in map. Value is: %d\n", value)
  } else {
    fmt.Printf("Mango is not present in map. Value is: %d\n", value)
  }
}

Output

Apple is present in map. Value is: 1
Mango is not present in map. Value is: 0


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.