Skip to content

Golang: Check if a Key Exists in a Map (If Contains)

Do you want to check if a key exists in a map? Golang has a very simple syntax for it.

You can check or even get the value in one line:

package main

import "fmt"

func main() {
	userRating := map[string]int{
		"Morteza": 30,
		"Tom":     22,
	}

	// Just check
	if _, ok := userRating["Morteza"]; ok {
		fmt.Println("Key Morteza exists")
	}

	// Check and get the value!
	if val, ok := userRating["Morteza"]; ok {
		fmt.Println("Rating for Morteza:", val)
	}
}

Tags:

Leave a Reply

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