Go Map Literals 🎯

beginner
6 min

Go Map Literals 🎯

Welcome to our deep dive into Go Map Literals! In this lesson, we'll explore how to create, manipulate, and understand Go's powerful key-value data structures known as maps. By the end of this lesson, you'll be able to confidently use maps in your Go projects. 💡 Pro Tip: Maps are essential for managing dynamic collections of data.

What are Go Maps? 📝

A Go Map is a collection of key-value pairs, similar to JavaScript objects or Python dictionaries. The keys in a Go map are unique, and they can be of any type, while values can be of any type too.

Creating a Go Map Literal ✅

To create a Go map, you use a map literal. Here's a simple example:

go
mapExample := map[string]int{ "Apple": 1, "Banana": 2, "Cherry": 3, }

In this example, we've created a map called mapExample with three key-value pairs. The keys are Apple, Banana, and Cherry, and their respective values are 1, 2, and 3.

Accessing and Manipulating Go Map Values 📝

To access a value in a Go map, you use the key associated with that value. Here's an example:

go
fmt.Println(mapExample["Apple"]) // Output: 1

To add a new key-value pair to a Go map, you can use the map[key] = value syntax. Here's an example:

go
mapExample["Orange"] = 4 fmt.Println(mapExample) // Output: map[Apple:1 Banana:2 Cherry:3 Orange:4]

Iterating through a Go Map 📝

To iterate through a Go map, you can use a for loop and the range keyword. Here's an example:

go
for key, value := range mapExample { fmt.Println("Key:", key, "Value:", value) }

This will output:

Key: Apple Value: 1 Key: Banana Value: 2 Key: Cherry Value: 3 Key: Orange Value: 4

Deleting a Key from a Go Map 📝

To delete a key from a Go map, you can use the delete function. Here's an example:

go
delete(mapExample, "Orange") fmt.Println(mapExample) // Output: map[Apple:1 Banana:2 Cherry:3]

Quiz 📝

Quick Quiz
Question 1 of 1

What is a Go Map?


With this lesson, you now have a solid understanding of Go Map literals and how to use them in your Go projects. 💡 Pro Tip: Maps are incredibly versatile and can be used in many different scenarios, so don't hesitate to experiment!

Stay tuned for our next lesson, where we'll explore Go functions and how to create your own! 🚀🚀🚀