Welcome To Golang By Example

Menu
  • Home
  • Blog
Menu

How to check if a map contains a key in Go (Golang)

Posted on July 11, 2023July 12, 2023 by admin

Below is the format to check if a key exists in the map

val, ok := mapName[key]

There are two cases

  • If the key existsvalvariable be the value of the key in the map andokvariable will be true
  • If the key doesn’t existvalvariable will be default zero value of value type andokvariable will be false

Let’s see an example

package main
import "fmt"
func main() {
//Declare
employeeSalary := make(map[string]int)
//Adding a key value
employeeSalary["Tom"] = 2000
fmt.Println("Key exists case")
val, ok := employeeSalary["Tom"]
fmt.Printf("Val: %d, ok: %t\n", val, ok)
fmt.Println("Key doesn't exists case")
val, ok = employeeSalary["Sam"]
fmt.Printf("Val: %d, ok: %t\n", val, ok)
}

Output

Key exists case
Val: 2000, ok: true
Key doesn't exists case
Val: 0, ok: false

In the above program when a key exists thenvalvariable is set to the actual value which is 2000 here andokvariable is true. When the key doesn’t exist thevalvariable is set to 0 which is the default zero value of int andokvariable is false. Thisokvariable is the best way to check if the key exists in a map or not

In case we only want to check if a key is present and val is not needed, then blank identifier i.e “_” can be used in place of val.

_, ok = employeeSalary["Sam"]

Also, check out our Golang advance tutorial Series – Golang Advance Tutorial

  • go
  • golang
  • Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2023 Welcome To Golang By Example | Design: Web XP