Check if Key Exists in Map in Golang

Monday, December 21, 2020 • 2 minutes to read

Golang2020to-the-pointgolang

Map

Map is a data structure which implements a hash table.

Map is a simple key-value storage. Map offers fast lookups, adds and deletes.

Zero Value Table

Map don't explicitly check if a key is created or not, instead if a key doesn't exists it returns the default value of value type.

Data type and their Default Value

Type Default Value
Numeric type(int, float) 0
Boolean false
String "” (empty string)

For Ex.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	m1 := map[string]int{
 7		"a": 1}
 8	m2 := map[string]bool{
 9		"a": true,
10	}
11
12	fmt.Printf("Value of key 'a' is %v\nValue of key 'b' is %v\n", m1["a"], m1["b"])
13	fmt.Printf("Value of key 'a' is %v\nValue of key 'b' is %v\n", m2["a"], m2["b"])
14}

Output

1Value of key 'a' is 1
2Value of key 'b' is 0
3Value of key 'a' is true
4Value of key 'b' is false

Check if key exist in a map or not

When value of the key is retrived from the map, it also returns a boolean value.

It is a widely used practice in golang to name ok to the boolean argument.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	m1 := map[string]int{
 7		"a": 1,
 8		"b": 2,
 9	}
10
11	value, ok := m1["a"]
12
13	fmt.Printf("Key 'a' exists %v and its value is %v\n", ok, value)
14
15	_, ok = m1["c"]
16
17	fmt.Printf("Key 'c' exists %v\n", ok)
18}

Output

1Key 'a' exists true and its value is 1
2Key 'c' exists false

Final Words

Map is a very powerful data structure. If order is not required then prefer map to array.


Golang2020to-the-pointgolang

PreviousHow to Format Golang Project

NextGolang String Replace