DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

GoLang - How to use maps

#go

When we start in Go and we already developed in another language, we can be perturbed about how maps works.

Declaration

The object type map doesn't exist in Go. A key word exist instead and it helps to create an object type based on maps with the following structure:

map[]

Examples

map[string]string
Enter fullscreen mode Exit fullscreen mode

For example, to create a map which will link a string key to a number, you will use : map[string]int

For a map used to link a rune to a book object : map[rune]book

Details on object type

As map object type doesn't directly exist, object types are identicals only if they have the same key type and value type.

map[rune]book != map[string]int
map[rune]book != map[string]book
map[rune]book != map[rune]int
map[rune]book == map[rune]book

Utilization

m := map[string]string{}   // Declare a map

m["p"] = 3                 // Add a value
m["p"] = 4                 // Update a value
fmt.Println(m)             // Print a map: "map[p:4]"

v := m["p"]                // Get a value: v == 4
v = m["p2"]                // Value not found: v == 0 (zero)

_, found := m["p"]         // found == true
_, found = m["p2"]         // found == false

if x, found := m["p"]; found {
    fmt.Println(x)
}                           // Print "4"

delete(m, "p")              // Delete a map
Enter fullscreen mode Exit fullscreen mode

I hope it will help you! 🍺


You want to support me?

Buy Me A Coffee

Top comments (0)