Home » Golang

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

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.

Code example:

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

Check key exists in map 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




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.