0
0
Goprogramming~15 mins

Iterating over maps in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterating over maps
📖 Scenario: You are managing a small store's inventory. You have a list of products with their stock counts. You want to check which products are available and print their names with the stock count.
🎯 Goal: Build a Go program that creates a map of products and their stock counts, then iterates over the map to print each product and its stock.
📋 What You'll Learn
Create a map called inventory with string keys and int values
Add a variable called minStock to set the minimum stock to consider a product available
Use a for loop with range to iterate over inventory
Print the product name and stock count only if the stock is greater than or equal to minStock
💡 Why This Matters
🌍 Real World
Managing inventory is a common task in stores and warehouses. Knowing how to store and check stock counts helps keep track of products.
💼 Career
Many programming jobs require working with maps or dictionaries to store and process data efficiently. Iterating over maps is a fundamental skill.
Progress0 / 4 steps
1
Create the inventory map
Create a map called inventory with these exact entries: "Apples": 10, "Bananas": 5, "Oranges": 0, "Grapes": 7
Go
Hint

Use map[string]int to create the map and include the exact key-value pairs.

2
Add minimum stock variable
Add an integer variable called minStock and set it to 1 to represent the minimum stock count to consider a product available.
Go
Hint

Declare minStock as an integer and assign it the value 1.

3
Iterate over the inventory map
Use a for loop with range to iterate over inventory with variables product and stock. Inside the loop, check if stock is greater than or equal to minStock.
Go
Hint

Use for product, stock := range inventory and an if statement to check stock.

4
Print available products
Inside the if block, use fmt.Println to print the product name and stock count in this exact format: "Apples: 10". Remember to import the fmt package.
Go
Hint

Use fmt.Println(product + ": " + fmt.Sprint(stock)) to print the product and stock.