Checking Stock
Part of the Logic & Flow section of Coddy's GO journey — lesson 46 of 68.
Challenge
EasyImplement a stock checking function for your inventory management system that safely retrieves product quantities and handles cases where products don't exist. This challenge builds on the inventory foundation from the previous lesson and adds error handling for stock queries.
You will receive two inputs:
- A string containing existing inventory data in the format
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"(e.g.,"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8") - A string containing stock check requests in the format
"product1,product2,product3"(e.g.,"Mouse,Tablet,Keyboard")
Your task is to:
- Use the same
Productstruct from the previous lesson withPrice(float64) andQuantity(int) fields - Parse the first input by splitting on commas to get individual product entries
- For each product entry, split on colons to get product name, price, and quantity
- Convert the price string to float64 and quantity string to int
- Create and populate the
inventorymap with the parsed product data - Create a function called
checkStockthat takes the inventory map and a product name as parameters and returns (int, error):- If the product exists in the inventory, return its quantity and nil
- If the product doesn't exist, return 0 and an error with the message
"product not found: [product_name]"
- Parse the second input by splitting on commas to get the list of products to check
- Display the stock checking header:
"Stock Check Results:" - For each product in the check list, call the
checkStockfunction and display the results:- If no error:
"[product_name]: [quantity] units in stock" - If error:
"[product_name]: Error - [error_message]"
- If no error:
- Count and display summary statistics:
"Check Summary:""Products checked: [total_number_of_products_checked]""Products found: [number_of_products_that_exist]""Products not found: [number_of_products_that_dont_exist]"
- Display the total stock for found products:
"Total stock for found products: [sum_of_quantities_for_existing_products] units"
- List any missing products:
- If there are missing products:
"Missing products: [comma_separated_list_of_missing_products]" - If no missing products:
"All requested products are available"
- If there are missing products:
Use the strings package to split the input strings, the strconv package to convert strings to numbers, the errors package to create error messages, and the fmt package for formatted output. This challenge demonstrates how to implement safe data retrieval with proper error handling, a fundamental pattern in inventory management systems.
Try it yourself
package main
import (
"bufio"
"fmt"
"os"
"sort"
"strconv"
"strings"
)
// Define the Product struct
type Product struct {
Price float64
Quantity int
}
func main() {
// Read input using bufio.Scanner to handle spaces properly
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
storeInfo := scanner.Text()
scanner.Scan()
productData := scanner.Text()
// 1. Parse store information (split by comma)
storeInfoParts := strings.Split(storeInfo, ",")
storeName := ""
location := ""
if len(storeInfoParts) >= 2 {
storeName = storeInfoParts[0]
location = storeInfoParts[1]
}
// 2. Parse product data (split by comma, then by colon for each product)
productEntries := strings.Split(productData, ",")
// 3. Create inventory map
inventory := make(map[string]Product)
// 4. Convert strings to appropriate types and populate inventory
for _, entry := range productEntries {
parts := strings.Split(entry, ":")
if len(parts) >= 3 {
productName := parts[0]
price, _ := strconv.ParseFloat(parts[1], 64)
quantity, _ := strconv.Atoi(parts[2])
inventory[productName] = Product{
Price: price,
Quantity: quantity,
}
}
}
// 5. Display store information
fmt.Printf("=== %s Inventory System ===\n", storeName)
fmt.Printf("Location: %s\n", location)
fmt.Printf("Inventory initialized with %d products\n", len(inventory))
// 6. Display current inventory (sorted alphabetically)
fmt.Println("Current Inventory:")
var productNames []string
for name := range inventory {
productNames = append(productNames, name)
}
sort.Strings(productNames)
for _, name := range productNames {
product := inventory[name]
fmt.Printf("- %s: $%.2f (Stock: %d)\n", name, product.Price, product.Quantity)
}
// 7. Calculate and display inventory statistics
totalProducts := len(inventory)
totalItems := 0
totalValue := 0.0
for _, product := range inventory {
totalItems += product.Quantity
totalValue += product.Price * float64(product.Quantity)
}
fmt.Println("Inventory Statistics:")
fmt.Printf("Total Products: %d\n", totalProducts)
fmt.Printf("Total Items in Stock: %d\n", totalItems)
fmt.Printf("Total Inventory Value: $%.2f\n", totalValue)
// 8. Display system status
fmt.Println("System Status: Ready")
fmt.Println("Inventory management system initialized successfully")
}All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter8Project: Simple Inventory
Project OverviewChecking Stock3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors