Problem overview
The cart now holds several items, stored in three slices of the same length: items (names), prices and quantities. The item at position 0 in items has the price at position 0 in prices and the quantity at position 0 in quantities, and so on. Slices that line up like this are called parallel slices.
The program prints one line per item in the form Name xQ: $subtotal, where the subtotal is the price times the quantity, then a final line with the total of all subtotals. For the starting data:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
The shirt costs 25 and the cart has two, so its line shows 50. The total is 50 + 40 + 60 + 45 = 195. This version replaces repeated hand-written lines with a loop, so the same code works for any number of items.
Approach: one pass, three jobs per item
Each item needs the same three things done to it: compute its subtotal, add that subtotal to a running total, and record its receipt line. A for loop over the positions does all three in one pass. After the loop, a single extra line reports the total, because the total is only known once every item has been counted.
The receipt lines are collected in a slice of strings, lines, and joined into one string at the end. This is simpler than building one long string with +, and it handles the newlines cleanly: the separator goes between lines only, so there is no stray newline after the last one.
Step by step
- Create an empty slice of strings named
lines. The literal[]string{}makes a slice with length 0 that can grow. - Start
totalat 0. A running total begins before any item is counted. - Loop with
for i := range items. Ranging over a slice with one variable gives the index. For four items,itakes 0, 1, 2 and 3. Because the three slices are parallel, the sameipicks the matching name, price and quantity. - Compute
sub. It isprices[i] * quantities[i], this item's subtotal. - Add it to
total. This is the running total: after the loop it holds the sum of every subtotal. - Append this item's line to
lines. The line joins the name," x", the quantity,": $"and the subtotal. The quantity and the subtotal areintvalues, and Go does not join anintto a string with+, so each goes throughstrconv.Itoa. The result ofappendmust be stored back inlines. - After the loop, append the
Total: $line. It sits outside the braces so that it runs once, not once per item. - Join the lines with
strings.Join(lines, "\n")and store the string inresult. - Print
resultwithfmt.Println.
The solution in Go
items := []string{"Shirt", "Pants", "Shoes", "Hat"}
prices := []int{25, 40, 60, 15}
quantities := []int{2, 1, 1, 3}
lines := []string{}
total := 0
for i := range items {
sub := prices[i] * quantities[i]
total = total + sub
lines = append(lines, items[i] + " x" + strconv.Itoa(quantities[i]) + ": $" + strconv.Itoa(sub))
}
lines = append(lines, "Total: $" + strconv.Itoa(total))
result := strings.Join(lines, "\n")
fmt.Println(result)
Go details worth knowing here:
appendreturns a slice. A slice has a length, andappendcannot change the length of the slice you pass in. It returns a new slice header, which may share the old backing array or use a larger one. The linelines = append(lines, ...)keeps that result. Writingappend(lines, "a")as a statement on its own does not compile: the compiler reportsappend(lines, "a") (value of type []string) is not used.rangewith one variable.for i := range itemsyields indices only. With two variables,for i, name := range itemswould also give a copy of each element, but this loop needs the index to reach into the other two slices anyway.- Imports. The code uses three packages:
fmtfor printing,strconvforItoaandstringsforJoin. strings.Join. It takes a[]stringand a separator and returns one string with the separator between each pair of elements. For a slice with one element it returns that element unchanged.
Edge cases and common mistakes
- Putting the total line inside the loop. It would be printed once per item, with a partial total each time. Keep it after the closing brace.
- Not storing what
appendreturns. A bareappend(lines, ...)is a compile error. Assigning the result to a different variable compiles, butlinesitself stays empty and the output has no rows. Always writelines = append(lines, ...). - Slices of different lengths. The loop runs over
items. Ifpricesorquantitiesis shorter, readingprices[i]past its end stops the program with an index out of range error. The three slices have to describe the same items. - A trailing newline. Joining with
strings.Joinadds no newline after the last line. Building the string by appending"\n"after every line would, and the result would not match the expected output exactly. - Mixing up the total.
totalsums subtotals (price times quantity), not prices. Addingprices[i]alone would give 140 instead of 195 for this cart.
Testing
- The starting cart prints the five lines above, ending with
Total: $195. - One item, a pen priced 3 with quantity 4, prints
Pen x4: $12and thenTotal: $12. - No items prints only
Total: $0, because the loop never runs but the final line still does.
