Sikau

Go · Day 5 · about 45 min

Project: A momo shop till

Orders, receipts and best-sellers with structs, slices and maps.

Didi's momo shop

A small momo shop in Patan wants a till: waiters add items to a table's order, the till prints a neat receipt, and at closing time the owner wants to know what sold best. It's a classic first Go program because it needs everything from this unit — structs for items and orders, slices for order lines, maps for counting, methods, sorting and formatted output.

Real point-of-sale systems are built from exactly these pieces. Get the data model right and the rest is a few short methods.

The data model

Three types: an Item has a name and a price in rupees; a Line is an item and a quantity; an Order is a table number and a slice of lines. Prices are whole rupees in an int — never use floating-point for money, because 0.1 can't be stored exactly.

type Item struct {
	Name  string
	Price int // rupees
}

type Line struct {
	Item Item
	Qty  int
}

type Order struct {
	Table int
	Lines []Line
}

Add must change the order, so it has a pointer receiver. When the same item is ordered twice it should increase the existing line rather than add a second one. Structs whose fields are all comparable can be compared with ==, so o.Lines[i].Item == item works.

The rest of this lesson

  • Formatting a receiptexplain
  • Widthspredict
  • Best-sellersorder
  • Format verbsmatch
  • Build the tillchallenge
  • Badge quizquiz
  • What you builtrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 10 lessons of Go