A shop takes payments by card, by PayPal and in cash. Every payment has an amount, in cents, and a total: the amount plus a processing fee. The total is worked out the same way for every payment; only the fee depends on the kind of payment. That is what an abstract class is for: it holds the shared part, says that every payment has a fee, and leaves the fee itself to each kind of payment.
Go has no classes, no inheritance and no abstract classes. As in the abstract-classes lesson, an interface plays the abstract class, and the shared part lives next to it:
- The interface
Paymentlists what every payment must have:getAmount() intandfee() int. - The struct
BasePaymentkeeps theamount, and its methodgetAmount()returns it. - The function
total(p Payment) intreturnsp.getAmount() + p.fee(): written once, it works for any payment. Go interfaces have no method bodies, so the shared method becomes a function. Card,PayPalandCasheach embedBasePayment, asPuppyembedsDogin the inheritance lesson, so they getamountandgetAmount()for free.NewCard(amount),NewPayPal(amount)andNewCash(amount)build them, and each writes its ownfee():
Cardpays 2%: its fee is amount × 2 / 100.PayPalpays 3% plus 30 cents: its fee is amount × 3 / 100 + 30.Cashcosts nothing: its fee is 0.
The methods take the struct as a receiver named this, as in the course's other lessons, and dividing two ints drops the fraction.
Every division rounds down: a card payment of 1999 cents has a fee of 39, not 39.98.
The starter code already has every type, the constructor functions and every method and function header: declare the interface's methods and the structs' contents, and write the bodies. For each test, the harness creates the payments in the order given and prints two lines: each payment's total, total(p), separated by spaces, and then the sum of all the fees. It calls them through the interface Payment, never through Card, PayPal or Cash.
Example 1:
Input:
NewCard(1999)
NewPayPal(500)
NewCash(700)
Output:
2038 545 700
84
Explanation: The card's fee is 1999 × 2 / 100 = 39 (39.98 rounded down), so its total is 2038. PayPal's fee is 500 × 3 / 100 + 30 = 45, total 545. Cash has no fee: total 700. The fees add up to 39 + 45 + 0 = 84.
Example 2:
Input:
NewCard(49)
NewPayPal(33)
NewCard(50)
Output:
49 63 51
31
Explanation: 49 × 2 / 100 is 0.98, rounded down to 0. PayPal's 33 × 3 / 100 is 0.99, rounded down to 0, plus 30. The second card's 50 × 2 / 100 is exactly 1. The fees are 0 + 30 + 1 = 31.
Example 3:
Input:
NewCard(0)
NewPayPal(0)
NewCash(0)
Output:
0 30 0
30
Explanation: Amounts can be 0. PayPal still adds its 30 cents.
Constraints:
- Every test has between 1 and 100 payments.
- Every amount is an integer from 0 to 106 cents.
Note:
Every fee and every total takes O(1) time.
Free plan: 30 tutor messages. PRO is unlimited.
