Problem overview
The lesson builds a VendingMachine that sells one kind of item at a fixed price. It remembers the money inserted so far, called the credit, sells an item when the credit is enough and returns the credit on request. The type is a struct with methods, and newVendingMachine() creates one.
- A new machine has
credit0 andprice150. Both arefloat64fields. insert(amount float64)adds to the credit and returns nothing.selectItem() stringreturns"Need N more"if the credit is below the price, where N is the missing amount as a whole number. The credit stays as it was. Otherwise it subtracts the price and returns"Dispensing!". Exact payment works, and extra money stays in the credit.refund() float64returns the whole credit and sets it to 0, so a second refund returns 0.
The driver inserts 50, so the machine answers Need 100 more. After 150 more the credit is 200, so it dispenses and keeps 50, which the refund returns. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, so the machine answers Need 50 more and the refund is 100.
Approach: state lives in the struct, methods change it
An object here is a struct value plus the methods that use it. The only state that changes is credit, so each method is a small operation on that one number:
insertincreases it.selectItemdecreases it by the price, but only when it can be paid for.refundresets it to zero.
Go has no constructors. A plain function, by convention named New... or here newVendingMachine, builds the value and returns a pointer to it. Fields that the literal leaves out get their zero value, so credit starts at 0 without being mentioned.
Step by step
- Declare
VendingMachineas a struct and give it twofloat64fields,creditandprice. Every machine built from this type keeps its own credit. - Write
newVendingMachine, with no parameters, returning a*VendingMachine. - Return
&VendingMachine{price: 150}. The&gives back the address of the new machine, not a copy, and the credit stays at its zero value. - Write
inserton*VendingMachinewith anamount float64parameter. Use a pointer receiver because it changes the machine. - Add to the credit:
machine.credit += amount. It adds to what is there already and doesn't replace it. - Write
selectItem, which returns astring. - Handle the short case first. If
machine.credit < machine.price, work outmissing := int(machine.price - machine.credit)and return"Need " + strconv.Itoa(missing) + " more". A refused purchase only reports; it must not touch the credit. The comparison is<, not<=, so exact payment goes through. - Subtract the price from the credit below the
if. This line is reached only when the credit covers the price. - Return
"Dispensing!". - Write
refund, which returns afloat64. - Save the credit in
refunded, resetmachine.creditto 0 and returnrefunded. The order matters: once the credit is reset, its old value is gone, so it has to be saved first.
The solution in Go
type VendingMachine struct {
credit float64
price float64
}
func newVendingMachine() *VendingMachine {
return &VendingMachine{price: 150}
}
func (machine *VendingMachine) insert(amount float64) {
machine.credit += amount
}
func (machine *VendingMachine) selectItem() string {
if machine.credit < machine.price {
missing := int(machine.price - machine.credit)
return "Need " + strconv.Itoa(missing) + " more"
}
machine.credit -= machine.price
return "Dispensing!"
}
func (machine *VendingMachine) refund() float64 {
refunded := machine.credit
machine.credit = 0
return refunded
}
func mainFunction() {
machine := newVendingMachine()
machine.insert(50)
fmt.Println(machine.selectItem())
machine.insert(150)
fmt.Println(machine.selectItem())
fmt.Println("Refunded: " + strconv.Itoa(int(machine.refund())))
machine.insert(150)
fmt.Println(machine.selectItem())
fmt.Println("Refunded: " + strconv.Itoa(int(machine.refund())))
machine.insert(100)
fmt.Println(machine.selectItem())
fmt.Println("Refunded: " + strconv.Itoa(int(machine.refund())))
}
The driver prints:
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
The Go details worth knowing:
- Pointer receivers. All three methods change
credit, so all three use*VendingMachine. With a value receiver,insertwould add to a copy and the machine's credit would stay at 0. - Each machine has its own state. After
m2.insert(10)on a second machine, the first machine's credit is unchanged. The credit belongs to the value that the constructor returned. - The zero value of
credit.&VendingMachine{price: 150}names onlyprice. Go sets every other field to its zero value, which is 0 for afloat64. A machine declared asvar z VendingMachinewould have a price of 0 too, so it would dispense for free. The constructor is what sets the price. - Converting to
intand to text.int(...)truncates toward zero, andstrconv.Itoaturns anintinto a string. Go won't join a number to a string with+on its own. - Several results in one expression. The driver passes
machine.selectItem()straight tofmt.Println. A method call can be used wherever a value of its result type is expected. - Local variable names.
missingandrefundedexist only inside their methods. Go reports a variable that is declared and never used, so each one must be read at least once, as both are here.
Edge cases and common mistakes
- Subtracting the price in the short case. The credit would shrink without a purchase, and the refund would come back too small. Subtract only when dispensing.
- Not subtracting after a sale. The leftover credit would be wrong and the refund too big. After the driver's first sale the refund must be 50, not 200.
- Using
<=in the check. Then exact payment, 150 for a 150 item, answersNeed 0 more. - Returning
machine.creditafter resetting it. The refund is always 0. Return the saved variable. - Refunding twice. The second call returns 0, because the first one emptied the credit.
- Credit left after a sale can buy again. After inserting 400, the machine dispenses with 250 left, then with 100 left, and then answers
Need 50 more. - Fractional amounts. The credit is a
float64, but the message shows a whole number, andint(...)cuts the fraction. With 149.5 inserted, the machine answersNeed 0 morewhile still refusing the sale. The lesson only inserts whole amounts, so this doesn't arise there.
Key takeaways
- A struct holds an object's state, and methods with pointer receivers change it.
- A
New...function plays the role of a constructor, and omitted fields start at their zero values. - Check the refusal case first and leave without touching the state.
- To return a value and clear it, save it in a variable first.
