Start learning free

LESSON 66 OF 69 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in Go: Structs, Methods and Composition

Practice Read the full explanation

A shop keeps its orders in a cart. Build two types that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • A struct LineItem with fields name string, price float64, quantity int.
  • func (item LineItem) subtotal() float64 returns item.price * float64(item.quantity).

Cart

  • A struct Cart with one field items []LineItem. The empty value Cart{} is an empty cart.
  • func (cart *Cart) add(item LineItem) appends the item to cart.items. It uses a pointer receiver (*Cart) so the change is kept in the caller's cart.
  • func (cart Cart) total() float64 returns the sum of the subtotals of all items: start total := 0.0, loop with for _, item := range cart.items, return total.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

Go has no classes: structs plus methods play that role. The driver is mainFunction() and prints with strconv.Itoa(int(...)) to show whole numbers.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

func mainFunction() {
	empty := Cart{}
	fmt.Println("Empty: " + strconv.Itoa(int(empty.total())))
	apple := LineItem{name: "Apple", price: 5, quantity: 3}
	fmt.Println("Subtotal: " + strconv.Itoa(int(apple.subtotal())))
	cart := Cart{}
	cart.add(apple)
	cart.add(LineItem{name: "Bread", price: 20, quantity: 3})
	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
	cart.add(LineItem{name: "Milk", price: 10, quantity: 2})
	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Declare the two structs first, then the methods.

for _, item := range cart.items { total += item.subtotal() }

type LineItem struct {
	name     string
	price    float64
	quantity int
}

func (item LineItem) subtotal() float64 {
	return item.price * float64(item.quantity)
}

type Cart struct {
	items []LineItem
}

func (cart *Cart) add(item LineItem) {
	cart.items = append(cart.items, item)
}

func (cart Cart) total() float64 {
	total := 0.0
	for _, item := range cart.items {
		total += item.subtotal()
	}
	return total
}

func mainFunction() {
	empty := Cart{}
	fmt.Println("Empty: " + strconv.Itoa(int(empty.total())))
	apple := LineItem{name: "Apple", price: 5, quantity: 3}
	fmt.Println("Subtotal: " + strconv.Itoa(int(apple.subtotal())))
	cart := Cart{}
	cart.add(apple)
	cart.add(LineItem{name: "Bread", price: 20, quantity: 3})
	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
	cart.add(LineItem{name: "Milk", price: 10, quantity: 2})
	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
}

STEP 1 OF 15
    Ctrl + Enter to check

    GO · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in Go, explained

    Problem overview

    The lesson models a shop's cart with two types that work together. A LineItem is one row of the cart: a name (string), a price (float64) and a quantity (int). Its method subtotal() returns the price times the quantity. A Cart holds many rows in a slice, items []LineItem. It has add(item LineItem) to append a row and total() to add up the subtotals.

    The cart has line items; it is not one. That relationship is called composition, and in Go it is expressed by putting one type in a field of another.

    In the driver, an empty cart has a total of 0. An apple at price 5 with quantity 3 has a subtotal of 15. After adding the apple and bread (price 20, quantity 3), the total is 75. After adding milk (price 10, quantity 2), it is 95.

    Approach: each type does its own arithmetic

    The cart doesn't need to know how a row's cost is worked out. It asks each row for its subtotal() and adds the answers. The row knows its own price and quantity. If the pricing rule changes later, only LineItem changes.

    The total is not stored anywhere. total() recalculates it from the rows each time it is called. Adding an item therefore changes the next total automatically, and no field can fall out of sync with the items. An empty cart has no rows to add, so the sum stays at its starting value of 0.

    Step by step

    1. Declare LineItem as a struct, Go's way of grouping data. There are no classes in Go: a struct holds the data and methods are declared next to it.
    2. Add the three fields: name string, price float64 and quantity int. A field is written as its name, then its type. The price is a float64 in case a price isn't whole, and a quantity is always a whole number.
    3. Declare subtotal with a LineItem receiver named item. The receiver ties the function to the type, so apple.subtotal() runs it with item set to apple.
    4. Return item.price * float64(item.quantity). Go refuses to multiply a float64 by an int, so the quantity is converted first.
    5. Declare Cart as a struct with one field, items, a slice of LineItem.
    6. Declare add with a pointer receiver (*Cart). It changes the cart, so it must work on the caller's cart and not on a copy.
    7. Append and store. cart.items = append(cart.items, item). append returns the longer slice, so the result has to be assigned back.
    8. Declare total with a plain Cart receiver. It only reads, so no pointer is needed.
    9. Start total := 0.0. The .0 makes it a float64 so it can hold subtotals. An empty cart returns this starting value.
    10. Loop with for _, item := range cart.items. range yields the index first and the row second. Go insists that every declared variable is used, so the underscore discards the index.
    11. Add item.subtotal() to total inside the loop.
    12. Return total after the loop, once every row has been added.

    The solution in Go

    type LineItem struct {
    	name     string
    	price    float64
    	quantity int
    }
    
    func (item LineItem) subtotal() float64 {
    	return item.price * float64(item.quantity)
    }
    
    type Cart struct {
    	items []LineItem
    }
    
    func (cart *Cart) add(item LineItem) {
    	cart.items = append(cart.items, item)
    }
    
    func (cart Cart) total() float64 {
    	total := 0.0
    	for _, item := range cart.items {
    		total += item.subtotal()
    	}
    	return total
    }
    
    func mainFunction() {
    	empty := Cart{}
    	fmt.Println("Empty: " + strconv.Itoa(int(empty.total())))
    	apple := LineItem{name: "Apple", price: 5, quantity: 3}
    	fmt.Println("Subtotal: " + strconv.Itoa(int(apple.subtotal())))
    	cart := Cart{}
    	cart.add(apple)
    	cart.add(LineItem{name: "Bread", price: 20, quantity: 3})
    	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
    	cart.add(LineItem{name: "Milk", price: 10, quantity: 2})
    	fmt.Println("Total: " + strconv.Itoa(int(cart.total())))
    }
    

    The driver prints:

    Empty: 0
    Subtotal: 15
    Total: 75
    Total: 95
    

    The Go details worth knowing:

    • No implicit numeric conversion. Writing item.price * item.quantity with a float64 and an int fails to compile with invalid operation: item.price * item.quantity (mismatched types float64 and int). Convert one side explicitly, as float64(item.quantity) does.
    • The loop variable is a copy. In for _, item := range cart.items, item is a copy of each row. Setting item.quantity = 100 inside such a loop leaves the cart unchanged: its total stays 95. To modify rows, loop over indexes and write cart.items[i].quantity = 1. The solution only reads, so the copy is harmless.
    • Pointer receiver on add. A method with a value receiver that appended to c.items would only change its own copy of the struct, and the caller's cart would still have zero items.
    • Calling cart.add(...) on a plain variable. cart := Cart{} is a value, not a pointer, yet cart.add(apple) compiles. Go takes the variable's address for you.
    • The zero value works. Cart{} has a nil slice with length 0. Ranging over it runs zero times and append accepts it, so an empty cart needs no setup.
    • Field names in struct literals. LineItem{name: "Apple", price: 5, quantity: 3} names every field, so the order doesn't matter. The untyped constant 5 becomes a float64 because the field has that type.
    • Printing whole numbers. strconv.Itoa needs an int, so the driver converts with int(...). That conversion drops the fractional part, which is safe here because the driver's prices are whole numbers. A cart holding one item at 19.99 has a total of 19.99, and int(...) of it is 19.
    • Variable and method with the same name. Inside total() the local variable total doesn't clash with the method, because a method is reached through its receiver, as in cart.total().

    Complexity

    Time: subtotal is O(1). add is amortized O(1). total is O(n) for n rows, because it visits each one once.

    Space: The cart stores n rows, which is O(n). total uses a single extra variable.

    Recalculating the total on every call costs O(n) each time, but it can never be stale. For a handful of rows that is the right trade.

    Edge cases and common mistakes

    • An empty cart. The loop doesn't run and total() returns 0.
    • Forgetting the float64(...) conversion. The compiler stops with the mismatched-types error above.
    • Starting with total := 0. That makes total an int, and total += item.subtotal() then fails to compile because the subtotal is a float64. Write 0.0.
    • Using for i, item := range without using i. Go reports i declared and not used. Use _.
    • A value receiver on add. It compiles, but the items are lost when the method returns.
    • Not assigning append's result. append(cart.items, item) on its own doesn't compile, because its value is unused.
    • Floating-point rounding. Three items at 1.1 total 3.3000000000000003, and int(...) of that is 3. Prices that aren't whole numbers can show tiny errors, so real shops often count in whole cents.
    • Storing the total in a field. A stored total would have to be updated by every method that changes the cart. Computing it on demand avoids that.

    Key takeaways

    • Structs hold data, methods with receivers add behaviour, and a struct that holds a slice of another struct is composition.
    • Let each type compute what it knows best: rows compute subtotals, the cart sums them.
    • Methods that change a struct need pointer receivers; read-only methods can use value receivers.
    • Go never converts between numeric types silently, so mix int and float64 only with an explicit conversion.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free