×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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

By IncludeHelp Last updated : October 05, 2024

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

This Go code demonstrates how to retrieve values from a map. It initializes a map m with a key-value pair. The first retrieval (m["apple"]) returns the value 1 and true, indicating the key exists. The second retrieval (m["mango"]) returns 0 and false, showing the key is absent.

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

This Go code demonstrates map operations by checking key existence. It initializes a map m with "apple" mapped to 1. The code checks if "apple" is present, printing its value. Then, it checks for "mango", which isn't present, resulting in printing the default value of 0.

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.