Go Program to Check if a Key Exists in a Map

Introduction

In Go, you can check if a key exists in a map by using the comma ok idiom. This allows you to safely access a value in the map and determine if the key is present. This guide will demonstrate how to check if a key exists in a map in Go.

Problem Statement

Create a Go program that:

  • Declares and initializes a map with some key-value pairs.
  • Prompts the user to enter a key to search for in the map.
  • Checks if the key exists in the map.
  • Displays a message indicating whether the key exists or not.

Example:

  • Input: Map: {"Apple": 5, "Banana": 3, "Cherry": 7}, Key to check: "Banana"
  • Output: Key "Banana" exists in the map.

Solution Steps

  1. Import the fmt Package: Use import "fmt" for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Create and Initialize the Map: Use a map literal to create and initialize a map with some key-value pairs.
  4. Prompt the User to Enter a Key: Use fmt.Scanln to take input from the user for the key to check.
  5. Check if the Key Exists in the Map: Use the comma ok idiom to check if the key exists in the map.
  6. Display the Result: Use fmt.Println to display whether the key exists in the map.

Go Program

package main

import "fmt"

/**
 * Go Program to Check if a Key Exists in a Map
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Create and initialize the map
    fruitMap := map[string]int{
        "Apple":  5,
        "Banana": 3,
        "Cherry": 7,
    }

    // Step 2: Prompt the user to enter a key to check
    var key string
    fmt.Print("Enter a key to check: ")
    fmt.Scanln(&key)

    // Step 3: Check if the key exists in the map using the comma ok idiom
    if value, ok := fruitMap[key]; ok {
        // Step 4: Display the result if the key exists
        fmt.Printf("Key \"%s\" exists in the map with value %d.\n", key, value)
    } else {
        // Step 4: Display the result if the key does not exist
        fmt.Printf("Key \"%s\" does not exist in the map.\n", key)
    }
}

Explanation

Step 1: Create and Initialize the Map

  • The map is created and initialized using a map literal. For example, fruitMap := map[string]int{"Apple": 5, "Banana": 3, "Cherry": 7} creates a map with three key-value pairs.

Step 2: Prompt the User to Enter a Key

  • The program prompts the user to enter a key to check using fmt.Print. The fmt.Scanln function reads the input and stores it in the key variable.

Step 3: Check if the Key Exists in the Map

  • The comma ok idiom is used to check if the key exists in the map. The syntax value, ok := map[key] checks if the key is present. If it is, ok will be true, and value will hold the corresponding value from the map.

Step 4: Display the Result

  • If the key exists, the program prints a message indicating that the key exists along with its value. If the key does not exist, the program prints a message indicating that the key does not exist.

Output Example

Example 1:

Enter a key to check: Banana
Key "Banana" exists in the map with value 3.

Example 2:

Enter a key to check: Mango
Key "Mango" does not exist in the map.

Example 3:

Enter a key to check: Cherry
Key "Cherry" exists in the map with value 7.

Conclusion

This Go program demonstrates how to check if a key exists in a map using the comma ok idiom. It covers basic programming concepts such as map manipulation, user input handling, and condition checking in Go. This example is useful for beginners learning Go programming and understanding how to safely access and manage map elements.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top