Getting started with Go — Maps

Matthew Boyd
1 min readDec 24, 2021

--

Maps are the equivalent to a dictionary in python. They’re a key value storage data structure.

The syntax for declaring a map would be as follows:

newMap := make(map[string]int)

In this declaration statement, we’ve created a variable of type map which will have the data type of string for the keys and the data type of int for the values.

The zero value of a map is nil.

We can create a map literal through the following syntax:

var newMap = map[string]string{"testing":"test", "123":"1234"}

In order to loop through a map we can do the following:

for key, value := range newMap{fmt.Println(key, value)
}

The two values that come out of a map are the key and the values.

Inserting into a map:

newMap["testing123123"] = "test_value"

Retrieving a single value by key:

results := newMap["testing123123"]

Deleting an element from a map:

delete(newMap, "testing123123")

Checking if a key exists in a map:

if elem, ok := newMap["testing123123]; ok{//If it does exist, do something
}

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet