DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Edited on

3

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay