Skip to content

Instantly share code, notes, and snippets.

@mkock
Last active September 6, 2020 11:32
Show Gist options
  • Select an option

  • Save mkock/0944d8b77e2487bec5c470b246710d2c to your computer and use it in GitHub Desktop.

Select an option

Save mkock/0944d8b77e2487bec5c470b246710d2c to your computer and use it in GitHub Desktop.
Bus Ride, code snippet 24
// Board adds the given Passenger to the Bus and charges them a ticket price calculated by chargeFn if they don't already have a paid ticket.
// Board returns false if the Passenger was not allowed to board the Bus.
func (b *Bus) Board(p *Passenger, chargeFn PriceCalculator) bool {
var allowed bool // Default value is false
if p.HasValidTicket {
allowed = true
} else {
amount := chargeFn(*p)
passenger := p.Charge(amount)
allowed = passenger.HasValidTicket
}
if allowed {
b.add(p)
}
return allowed
}
// Charge prints a message that the Passenger has been charged "amount" money, and returns a copy with validTicket = true.
func (p Passenger) Charge(amount float64) Passenger {
if p.HasValidTicket {
return p // We already charged this Passenger.
}
fmt.Printf("Passenger with SSN %s: charged %.2f of arbitrary money\n", p.SSN, amount)
p.HasValidTicket = true
return p
}
// PriceCalculator is the type used by BusCompany to determine the ticket price for a Passenger.
// PriceCalculator returns the ticket price in the local currency.
type PriceCalculator func(p Passenger) float64
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment