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
- Declare
LineItemas 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. - Add the three fields:
name string,price float64andquantity int. A field is written as its name, then its type. The price is afloat64in case a price isn't whole, and a quantity is always a whole number. - Declare
subtotalwith aLineItemreceiver nameditem. The receiver ties the function to the type, soapple.subtotal()runs it withitemset toapple. - Return
item.price * float64(item.quantity). Go refuses to multiply afloat64by anint, so the quantity is converted first. - Declare
Cartas a struct with one field,items, a slice ofLineItem. - Declare
addwith a pointer receiver (*Cart). It changes the cart, so it must work on the caller's cart and not on a copy. - Append and store.
cart.items = append(cart.items, item).appendreturns the longer slice, so the result has to be assigned back. - Declare
totalwith a plainCartreceiver. It only reads, so no pointer is needed. - Start
total := 0.0. The.0makes it afloat64so it can hold subtotals. An empty cart returns this starting value. - Loop with
for _, item := range cart.items.rangeyields the index first and the row second. Go insists that every declared variable is used, so the underscore discards the index. - Add
item.subtotal()tototalinside the loop. - Return
totalafter 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.quantitywith afloat64and anintfails to compile withinvalid operation: item.price * item.quantity (mismatched types float64 and int). Convert one side explicitly, asfloat64(item.quantity)does. - The loop variable is a copy. In
for _, item := range cart.items,itemis a copy of each row. Settingitem.quantity = 100inside such a loop leaves the cart unchanged: its total stays 95. To modify rows, loop over indexes and writecart.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 toc.itemswould 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, yetcart.add(apple)compiles. Go takes the variable's address for you. - The zero value works.
Cart{}has anilslice with length 0. Ranging over it runs zero times andappendaccepts 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 constant5becomes afloat64because the field has that type. - Printing whole numbers.
strconv.Itoaneeds anint, so the driver converts withint(...). 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, andint(...)of it is 19. - Variable and method with the same name. Inside
total()the local variabletotaldoesn't clash with the method, because a method is reached through its receiver, as incart.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 makestotalanint, andtotal += item.subtotal()then fails to compile because the subtotal is afloat64. Write0.0. - Using
for i, item := rangewithout usingi. Go reportsi 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
intandfloat64only with an explicit conversion.
