Recap - Understanding Pointers
Part of the Fundamentals section of Coddy's GO journey — lesson 66 of 109.
Challenge
MediumIn this challenge, you'll build a simple inventory management system for a small store. You'll use pointers to update inventory quantities, calculate values, and track changes.
Complete the three functions below:
-
updateQuantity(quantity *int, change int) (int, bool)
Modify the value atquantityby addingchange(negative for sales, positive for restocks).
If the result would go below0, set*quantityto0instead.
Return the new quantity and a boolean that istrueif the item is now out of stock (*quantity == 0). -
calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
CalculatetotalValueasfloat64(quantity) * price.
IftotalValueis greater than*highestValue, update*highestValueand set*mostValuableItemtoitemNameusing the pointers.
ReturntotalValue. -
displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
Print each item's name, quantity (dereferenced from its pointer), and calculated value usingfmt.Printf.
Format:Apples: 10 (Value: $5.00)— use%.2ffor prices.
The expected output for the initial inventory is:
Initial Inventory: Apples: 10 (Value: $5.00) Oranges: 15 (Value: $10.50) Bananas: 8 (Value: $2.40) Total inventory value: $17.90 Most valuable item: Oranges
Tip: Use *quantity to read or write the value a pointer points to. For example, *quantity += change modifies the original variable directly.
Try it yourself
package main
import "fmt"
// updateQuantity updates the quantity of an item and returns the new quantity
// and whether the item is out of stock (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
// TODO: Update the quantity pointer and return the new value and out-of-stock status
return 0, false
}
// calculateValue calculates the total value of an item based on quantity and price
// It also updates the mostValuableItem if this item is more valuable
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
// TODO: Calculate the total value, update mostValuableItem if needed, and return the total value
return 0.0
}
// displayInventory prints the inventory details
// It takes pointers to allow the function to show real-time data
func displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64) {
fmt.Printf("Apples: %d (Value: $%.2f)\n", *apples, float64(*apples) * applePrice)
fmt.Printf("Oranges: %d (Value: $%.2f)\n", *oranges, float64(*oranges) * orangePrice)
fmt.Printf("Bananas: %d (Value: $%.2f)\n", *bananas, float64(*bananas) * bananaPrice)
}
func main() {
// Initialize inventory
apples := 10
oranges := 15
bananas := 8
// Prices
applePrice := 0.5 // $0.50 each
orangePrice := 0.7 // $0.70 each
bananaPrice := 0.3 // $0.30 each
// Track the most valuable item
var mostValuableItem string
var highestValue float64
// Display initial inventory
fmt.Println("Initial Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Calculate initial values and find most valuable item
appleValue := calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue := calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue := calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// Simulate some sales
fmt.Println("Processing sales...")
_, applesOutOfStock := updateQuantity(&apples, -4) // Sell 4 apples
_, orangesOutOfStock := updateQuantity(&oranges, -8) // Sell 8 oranges
_, bananasOutOfStock := updateQuantity(&bananas, -10) // Try to sell 10 bananas (more than we have)
// Check if any items are out of stock
if applesOutOfStock {
fmt.Println("Apples are out of stock!")
}
if orangesOutOfStock {
fmt.Println("Oranges are out of stock!")
}
if bananasOutOfStock {
fmt.Println("Bananas are out of stock!")
}
// Display updated inventory
fmt.Println("\nUpdated Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for recalculation
mostValuableItem = ""
highestValue = 0
// Recalculate values
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// Restock items
fmt.Println("Restocking...")
updateQuantity(&apples, 5) // Add 5 apples
updateQuantity(&oranges, 10) // Add 10 oranges
updateQuantity(&bananas, 12) // Add 12 bananas
// Display final inventory
fmt.Println("\nFinal Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for final calculation
mostValuableItem = ""
highestValue = 0
// Final value calculation
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n", mostValuableItem)
}All lessons in Fundamentals
4Comparison & Logical Operators
Comparison Operators - Part 1Comparison Operators - Part 2Logical AND OperatorLogical OR OperatorLogical NOT OperatorOperator Precedence BasicsRecap - Making Comparisons7Control Flow: Loops
What The `for` Loop ExplainedFor Loop - BasicFor Loop - Condition OnlyThe `break` KeywordThe `continue` KeywordNested LoopsRecap - Repeating Actions2Variables and Basic Data Types
What is a variableType Inference with `:=`Integers (int)Floating-Point NumbersBooleansStringsZero ValuesConstantsNaming ConventionsRecap - Variables and Types5Basic Input/Output
Formatted OutputFormat VerbsPrinting TypesGetting Basic User InputRecap - Input and Output8Functions
Understanding FunctionsDeclaring a FunctionCalling FunctionsFunction ParametersReturning a Single ValueReturning Multiple ValuesNamed Return ValuesFunction Scope BasicsRecap - Creating Reusable Code3Basic Operators
Arithmetic OperatorsDivision OperatorThe Modulo OperatorAssignment OperatorAugmented Assignment OperatorsIncrement and DecrementRecap - Calculations6Control Flow: Conditionals
The `if` StatementThe `else` KeywordThe `else if` KeywordVariable Shadowing in `if`Initializing VariablesThe `switch` StatementSwitch with ExpressionsSwitch without ExpressionThe `fallthrough` KeywordRecap - Making Decisions9Pointers
What is a Pointer?Declaring Pointer VariablesThe Address-Of OperatorDereferencing PointersUsing Pointers in FunctionsNil PointersRecap - Understanding Pointers