Start learning free

LESSON 192 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Go: Summing a Cart with a for Loop

Practice Read the full explanation

Use a for loop over parallel slices to compute a running total across several items.

You start with:

items := []string{"Shirt", "Pants", "Shoes", "Hat"}
prices := []int{25, 40, 60, 15}
quantities := []int{2, 1, 1, 3}

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with fmt.Println(result).

Use lines := []string{} and total := 0 before the loop, then append each formatted line.

Call strings.Join(lines, "\n") at the end.

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)

STEP 1 OF 9
    Ctrl + Enter to check

    GO · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Go, explained

    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

    1. Create an empty slice of strings named lines. The literal []string{} makes a slice with length 0 that can grow.
    2. Start total at 0. A running total begins before any item is counted.
    3. Loop with for i := range items. Ranging over a slice with one variable gives the index. For four items, i takes 0, 1, 2 and 3. Because the three slices are parallel, the same i picks the matching name, price and quantity.
    4. Compute sub. It is prices[i] * quantities[i], this item's subtotal.
    5. Add it to total. This is the running total: after the loop it holds the sum of every subtotal.
    6. Append this item's line to lines. The line joins the name, " x", the quantity, ": $" and the subtotal. The quantity and the subtotal are int values, and Go does not join an int to a string with +, so each goes through strconv.Itoa. The result of append must be stored back in lines.
    7. After the loop, append the Total: $ line. It sits outside the braces so that it runs once, not once per item.
    8. Join the lines with strings.Join(lines, "\n") and store the string in result.
    9. Print result with fmt.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:

    • append returns a slice. A slice has a length, and append cannot 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 line lines = append(lines, ...) keeps that result. Writing append(lines, "a") as a statement on its own does not compile: the compiler reports append(lines, "a") (value of type []string) is not used.
    • range with one variable. for i := range items yields indices only. With two variables, for i, name := range items would 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: fmt for printing, strconv for Itoa and strings for Join.
    • strings.Join. It takes a []string and 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 append returns. A bare append(lines, ...) is a compile error. Assigning the result to a different variable compiles, but lines itself stays empty and the output has no rows. Always write lines = append(lines, ...).
    • Slices of different lengths. The loop runs over items. If prices or quantities is shorter, reading prices[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.Join adds 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. total sums subtotals (price times quantity), not prices. Adding prices[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: $12 and then Total: $12.
    • No items prints only Total: $0, because the loop never runs but the final line still does.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free