Follow

Follow

How to check efficiently if a map contains a key in Go?

Maheshwar Ligade's photo
Maheshwar Ligade
·May 3, 2023·

2 min read

Play this article

Table of contents

  • Introduction:
  • Using the _, ok idiom:
  • Using the val, ok := m[key] syntax:
  • Using the for range loop:
  • Conclusion:

Introduction:

Working with maps is an essential part of programming in Go. However, sometimes you may need to check whether a particular key exists in a map or not. In this article, we will discuss different ways to check if a map contains a key in Go.

  1. Using the _, ok idiom:

The simplest way to check if a key exists in a map is by using the _, ok idiom. This idiom returns two values: the value of the key and a boolean value that indicates whether the key exists in the map or not.

// Define a map
    m := map[string]int{
        "apple":  1,
        "banana": 2,
        "orange": 3,
    }

    // Check if the key exists
    if _, ok := m["apple"]; ok {
        fmt.Println("Key exists!")
    } else {
        fmt.Println("Key does not exist!")
    }
  1. Using the val, ok := m[key] syntax:

Another way to check if a key exists in a map is by using the val, ok := m[key] syntax. This syntax returns the value of the key and a boolean value that indicates whether the key exists in the map or not.

// Define a map
    m := map[string]int{
        "apple":  1,
        "banana": 2,
        "orange": 3,
    }

    // Check if the key exists
    val, ok := m["apple"]
    if ok {
        fmt.Println("Key exists with value:", val)
    } else {
        fmt.Println("Key does not exist!")
    }
  1. Using the for range loop:

Another way to check if a key exists in a map is by using the for range loop. This loop iterates over all the key-value pairs in the map, allowing you to check if the key exists.

// Define a map
    m := map[string]int{
        "apple":  1,
        "banana": 2,
        "orange": 3,
    }

    // Check if the key exists
    for key := range m {
        if key == "apple" {
            fmt.Println("Key exists!")
            break
        }
    }

Conclusion:

Checking if a key exists in a map is an important task when working with maps in Go. In this article, we have discussed three different ways to check if a map contains a key in Go. Each method has its own advantages and disadvantages, and the choice of method depends on the specific use case.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this