Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to check if a Golang map contains a key

Gutha Vamsi Krishna

Overview

In this shot, we will learn to check if the Golang map contains a key.

We can use if statements in Golang to check if a key is present in the map or not.

Syntax

if val, ok := map["key"]; ok {
    //do
}else{

}

Return value

If a map has key, then ok has the bool value true, and val contains a value of that key. We can have an else statement to handle if the map doesn’t contain the required key.

Example

In the example below, we have a map students, which contains student names as keys and their age as the value.

We will get the age of a student and handle the else case if a student isn’t found.

Code

package main

//program execution starts here
func main(){

  //declare a map
  students := map[string]int{
    "john": 10,
    "james": 12,
    "mary":13,
    }

  //check if john is present in map
  if val, ok := students["john"]; ok {
    print(val)
  }else{
    print("No record found")
  }
}

Explanation

In the above code:

  • Line 4: We start program execution from the main() function in Golang.

  • Line 7: We declare and initialize the map students where the key is of string type, which holds student’s name, and value of int type, which holds student’s age.

  • Line 14: We check if map students and a key john is present or not.

    • Line 15: If present, it displays the value, which is the student’s age.
    • Line 17: If not present, it prints No record found.

When we run the above code snippet, we see the output as 10, which is john's age.

If we try to pass student name robert, which is not in the map students, then the output is No record found. This is because robert is not present in the map students.

package main

//program execution starts here
func main(){

  //declare a map
  students := map[string]int{
    "john": 10,
    "james": 12,
    "mary":13,
    }

  //check if john is present in map
  if val, ok := students["robert"]; ok {
    print(val)
  }else{
    print("No record found")
  }
}

RELATED TAGS

golang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring