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

Jetbrains image

Don’t Become a Data Breach Headline

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. Is your CI/CD protected? Check out these nine practical tips to keep your CI/CD secure—without adding friction.

Learn more

Top comments (0)

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video 📺

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay