Go · Level 2 Structs

Methods and Pointer Receivers

Give a Go struct methods that change it, and see why a value receiver silently updates a copy while a pointer receiver updates the real wallet.

  • a method has a receiver
  • a value receiver gets a copy
  • a pointer receiver changes the struct

A method is a function with a receiver: func (w *Wallet) Deposit(n int). Trap: with a value receiver, (w Wallet), the method changes a copy and the balance never moves. Use a pointer receiver to change the struct.

type Counter struct{ n int }

func (c Counter) Bad()  { c.n++ } // a copy
func (c *Counter) Inc() { c.n++ } // original

Give Wallet three methods: Deposit(amount int), Withdraw(amount int) bool (false and no change if the balance is too low) and Balance() int. Example: deposit 50, withdraw 20 → balance 30.

solution.go
Test Suites Pending
Output