Start learning free

LESSON 194 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Go: Group Totals by Category with a Map

Practice Read the full explanation

Use a map to accumulate totals per category while looping over parallel slices, then list the categories sorted by name.

You start with:

items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
prices := []int{2, 3, 25, 1, 40}
categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}

Build:

Clothes: $65
Food: $6

Rules:

  • Build a map totals that maps each category to the sum of the prices of its items.
  • Loop with an index. For each item, add its price to the total of categories[i]; a category you have not seen yet counts as 0.
  • Make one line per category, in the format "Category: $total", sorted alphabetically by category name (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with fmt.Println(result).

A map gives 0 for a missing key, so totals[cat] = totals[cat] + prices[i] just works.

Collect the keys into a slice and call sort.Strings(keys) before building the lines.

items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
prices := []int{2, 3, 25, 1, 40}
categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}

totals := map[string]int{}
for i := range items {
    cat := categories[i]
    totals[cat] = totals[cat] + prices[i]
}
lines := []string{}
keys := make([]string, 0, len(totals))
for cat := range totals {
    keys = append(keys, cat)
}
sort.Strings(keys)
for _, cat := range keys {
    lines = append(lines, cat + ": $" + strconv.Itoa(totals[cat]))
}
result := strings.Join(lines, "\n")
fmt.Println(result)

STEP 1 OF 13
    Ctrl + Enter to check

    GO · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Go, explained

    Problem overview

    The cart has five items in parallel slices: items, prices and categories. Each item has a name, a price and a category such as Food or Clothes. The program adds up the prices per category and prints one line for each category, sorted alphabetically by name:

    Clothes: $65
    Food: $6

    The shirt (25) and the pants (40) are clothes, giving 65. The apple (2), the bread (3) and the banana (1) are food, giving 6. Clothes comes first because C sorts before F, even though the first item in the cart is food.

    Approach: accumulate in a map, then sort the keys

    The categories are not known in advance, and one category can show up many times, in any order. A map from category to total handles this: for each item, add its price to the entry for its category.

    The first item of a new category has no entry yet. In Go, reading a missing key from a map[string]int gives 0, so totals[cat] + prices[i] works on the first item too, with no special case.

    The second problem is order. Go deliberately makes map iteration order random, so ranging over the map directly would print the categories in an order that can change from run to run. The fix is to copy the keys into a slice, sort the slice, and build the lines by walking the sorted slice and looking each total up in the map.

    Step by step

    1. Create the map. totals := map[string]int{} is empty, with string keys (categories) and int values (running totals).
    2. Loop over the positions with for i := range items. The same i selects the matching price and category from the parallel slices.
    3. Read the category. cat := categories[i] gives the category of the current item.
    4. Update the total. totals[cat] = totals[cat] + prices[i] reads the current total (0 if the category is new), adds the price and stores the sum back.
    5. Create the empty lines slice for the output rows.
    6. Create keys. make([]string, 0, len(totals)) builds a slice with length 0 and room reserved for as many strings as the map has keys. The capacity only avoids regrowing; the slice is still empty.
    7. Collect the categories. for cat := range totals ranges over a map; with one variable it yields the keys, in no fixed order.
    8. Append each key to keys, storing the result of append back in keys.
    9. Sort the keys with sort.Strings(keys). It rearranges the slice in place and returns nothing.
    10. Loop over the sorted keys. for _, cat := range keys gives an index and a value; the blank identifier _ discards the index, which is not needed.
    11. Append a row per category: the category, ": $" and the total from the map, converted with strconv.Itoa.
    12. Join and print. strings.Join(lines, "\n") puts a newline between rows only, and fmt.Println prints the result.

    The solution in Go

    items := []string{"Apple", "Bread", "Shirt", "Banana", "Pants"}
    prices := []int{2, 3, 25, 1, 40}
    categories := []string{"Food", "Food", "Clothes", "Food", "Clothes"}
    
    totals := map[string]int{}
    for i := range items {
        cat := categories[i]
        totals[cat] = totals[cat] + prices[i]
    }
    lines := []string{}
    keys := make([]string, 0, len(totals))
    for cat := range totals {
        keys = append(keys, cat)
    }
    sort.Strings(keys)
    for _, cat := range keys {
        lines = append(lines, cat + ": $" + strconv.Itoa(totals[cat]))
    }
    result := strings.Join(lines, "\n")
    fmt.Println(result)
    

    Go details worth knowing here:

    • Printing a map directly. fmt.Println(totals) shows map[Clothes:65 Food:6]. The fmt package happens to print maps with their keys sorted, but that is formatting, not a property of the map. Looping over a map yourself gives no order, which is why this lesson sorts the keys.
    • Reusing the name cat. The first cat belongs to the first loop body, the second to the range totals loop, and the third to the loop over keys. Each lives only inside its own loop, so there is no clash.
    • Imports. The program uses fmt, sort, strconv and strings. An unused import is a compile error in Go, as is an unused variable.
    • sort.Strings compares bytes. Uppercase letters sort before lowercase ones, so "Food" sorts before "food", and a category that starts with a capital comes before every category that starts with a lowercase letter.
    • Maps start empty with map[string]int{}. Declaring var totals map[string]int gives a nil map, which can be read but panics when you write to it.

    Edge cases and common mistakes

    • Skipping the sort. Ranging over totals to build the lines gives the right numbers in an unpredictable order, so the lesson's tests would pass on some runs and fail on others.
    • Different capitalization. Categories food and Food are two keys. For items with those categories and prices 1 and 2, the output is Food: $2 then food: $1.
    • An empty cart. The map is empty, lines stays empty, and strings.Join returns an empty string, so a blank line is printed.
    • Writing the sum with a check for missing keys. An if that tests whether the key exists before adding is unnecessary here, since the zero value already starts each total at 0.
    • Using len(totals) as the length. make([]string, len(totals)) would create a slice that already holds empty strings, and appending to it would put the categories after them. The reference uses length 0 and the map size as capacity.

    Testing

    • The starting cart prints Clothes: $65 and Food: $6.
    • A single item, a lamp at 18 in Home, prints Home: $18.
    • Prices 1, 2 and 3 with categories food, Food and Clothes print Clothes: $3, Food: $2 and food: $1.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free