Start learning free

LESSON 67 OF 69 · PROJECTS: OBJECT-ORIENTED

Vending Machine in Go: A Struct with State and Methods

Practice Read the full explanation

Build a VendingMachine type (a struct with methods) for a machine that sells one kind of item for a fixed price. It keeps the money inserted so far (the credit), sells an item when the credit is enough, and gives the remaining credit back on request. A new object is made with newVendingMachine().

Rules:

  • State. A new machine has credit 0 and price 150 (every item costs 150). Give the struct the fields credit float64 and price float64; newVendingMachine() returns &VendingMachine{price: 150} (the credit starts at Go's zero value, 0).
  • func (machine *VendingMachine) insert(amount float64) adds amount to the credit. Nothing is printed or returned.
  • func (machine *VendingMachine) selectItem() string tries to buy one item and returns a string:
    • If the credit is less than the price, return "Need N more", where N is the missing amount (price - credit) as a whole number, for example "Need 100 more". The credit does not change.
    • Otherwise (the credit is equal to or greater than the price, so exact payment works), subtract the price from the credit and return "Dispensing!". Any extra money stays in the credit.
  • func (machine *VendingMachine) refund() float64 returns the whole credit and sets it back to 0, so asking again right away returns 0.

You start with this driver below your code:

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())))
}

Walk through it: 50 is not enough, so you see Need 100 more. After 150 more the credit is 200, so the machine dispenses and keeps 50 (200 - 150), and the refund is 50. Then 150 is exact payment: it dispenses and the refund is 0. Finally 100 is short by 50, the credit stays 100, and the refund is 100.

Expected output:

Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100

Convert the missing amount with int(machine.price - machine.credit) and turn it into text with strconv.Itoa(...). Do the subtraction only when the item is dispensed, not when the credit is too low. If you forget it, the leftover credit is wrong and the refund is too big.

In the refund method, save the credit first, then reset it to 0, then return what you saved. Return the saved variable, not machine.credit.

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
}

STEP 1 OF 17
    Ctrl + Enter to check

    GO · PROJECTS: OBJECT-ORIENTED

    Vending Machine in Go, explained

    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 credit 0 and price 150. Both are float64 fields.
    • insert(amount float64) adds to the credit and returns nothing.
    • selectItem() string returns "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() float64 returns 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:

    • insert increases it.
    • selectItem decreases it by the price, but only when it can be paid for.
    • refund resets 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

    1. Declare VendingMachine as a struct and give it two float64 fields, credit and price. Every machine built from this type keeps its own credit.
    2. Write newVendingMachine, with no parameters, returning a *VendingMachine.
    3. Return &VendingMachine{price: 150}. The & gives back the address of the new machine, not a copy, and the credit stays at its zero value.
    4. Write insert on *VendingMachine with an amount float64 parameter. Use a pointer receiver because it changes the machine.
    5. Add to the credit: machine.credit += amount. It adds to what is there already and doesn't replace it.
    6. Write selectItem, which returns a string.
    7. Handle the short case first. If machine.credit < machine.price, work out missing := 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.
    8. Subtract the price from the credit below the if. This line is reached only when the credit covers the price.
    9. Return "Dispensing!".
    10. Write refund, which returns a float64.
    11. Save the credit in refunded, reset machine.credit to 0 and return refunded. 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, insert would 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 only price. Go sets every other field to its zero value, which is 0 for a float64. A machine declared as var z VendingMachine would have a price of 0 too, so it would dispense for free. The constructor is what sets the price.
    • Converting to int and to text. int(...) truncates toward zero, and strconv.Itoa turns an int into 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 to fmt.Println. A method call can be used wherever a value of its result type is expected.
    • Local variable names. missing and refunded exist 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, answers Need 0 more.
    • Returning machine.credit after 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, and int(...) cuts the fraction. With 149.5 inserted, the machine answers Need 0 more while 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.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free