In this lesson, we have introduced concepts and syntax related to using maps in our Go programs. Let’s take a moment to review what we’ve learned.
Map Creation
Maps can be initialized with or without data.
customers := map[string]int employees := map[string]int{ "John": 1001, "Ezira": 1002, "Emily": 1003, }
Accessing
We can look up values with a key. We can also get a status
value to determine if the key was set in the map.
count,status := inventory["sporks"] if status { fmt.Println("we have %d sporks!", count) } else { fmt.Println("what is a spork?") }
Adding and Updating
Adding and updating key-values in our map follows the same format:
customers["George"] = 10.50
Deleting
We use the delete
function to remove key-value pairs from our map:
delete(inventory, "sporks")
Conclusion
We can use maps for all sorts of things! Examples include:
- Organizing collections such as types of coins, kinds of donuts, etc.
- Mapping different data such as people names to balance due.
- Storing frequently used content for a user.
We now can use maps in our programs! Try this out anywhere where we need to associate related information.
Instructions
Take a look at the workspace for this exercise. It reviews many of the concepts we’ve learned in this lesson. You aren’t required to do anything, but we suggest:
- Adding a new map to keep track of the prices of different kinds of donuts.
- Checking if an order can be fulfilled.
- Removing the customer after they have finished their order.
Notice that we use structs in this review exercise. If you haven’t used structs before you can learn about them in the next lesson in this course!