Recap - Dynamic Lists
Part of the Fundamentals section of Coddy's GO journey — lesson 83 of 109.
Challenge
MediumLet's practice working with slices in Go by creating a simple shopping list manager!
Your task is to implement several functions that manipulate a shopping list:
addItems: Add new items to the shopping listremoveItem: Remove an item from the list by indexfindExpensiveItems: Find items with prices above a thresholdcalculateTotalCost: Calculate the total cost of all items
Each item in the shopping list is represented by a string (name) and a float64 (price). The main function demonstrates all these operations working together.
Try it yourself
package main
import "fmt"
// addItems adds new items and their prices to the shopping list
func addItems(names []string, prices []float64, newNames []string, newPrices []float64) ([]string, []float64) {
// Your code here
return names, prices
}
// removeItem removes an item at the specified index
func removeItem(names []string, prices []float64, index int) ([]string, []float64) {
// Your code here
return names, prices
}
// findExpensiveItems returns items with prices above the threshold
func findExpensiveItems(names []string, prices []float64, threshold float64) []string {
// Your code here
return nil
}
// calculateTotalCost returns the sum of all prices
func calculateTotalCost(prices []float64) float64 {
// Your code here
return 0
}
func main() {
// Initialize empty shopping lists
names := []string{}
prices := []float64{}
// Add initial items
initialNames := []string{"Apples", "Milk", "Bread"}
initialPrices := []float64{2.99, 3.49, 2.29}
names, prices = addItems(names, prices, initialNames, initialPrices)
// Print the initial shopping list
fmt.Println("Initial Shopping List:")
for i := range names {
fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
}
// Calculate and print total cost
total := calculateTotalCost(prices)
fmt.Printf("\nTotal Cost: $%.2f\n", total)
// Find and print expensive items
priceThreshold := 3.00
expensiveItems := findExpensiveItems(names, prices, priceThreshold)
fmt.Printf("\nExpensive Items (above $%.2f):\n", priceThreshold)
for _, item := range expensiveItems {
fmt.Println(item)
}
// Add a new item
names, prices = addItems(names, prices, []string{"Cheese"}, []float64{4.99})
// Remove an item
names, prices = removeItem(names, prices, 1)
fmt.Println("\nRemoved item at index 1")
// Print the final shopping list
fmt.Println("\nFinal Shopping List:")
for i := range names {
fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
}
}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 Decisions