Project: Mini Bank Ledger
Time to bring together a lot of what you've learned: structs, maps, slices, enums, interfaces (error and fmt.Stringer), plus sentinel errors, custom errors, and wrapping with %w.
You'll build a mini bank for a campus cooperative. Part of the code is already provided:
- The
Jenisenum (Setoran,Penarikan,TransferMasuk,TransferKeluar, that is deposit, withdrawal, incoming transfer, outgoing transfer), along with itsString()method. - The
Transaksi{Jenis, Jumlah, Lawan}struct.Lawanis the other account's name in a transfer, and empty for deposits and withdrawals. - The sentinel errors
ErrAkunTidakAda,ErrAkunSudahAda,ErrJumlahTidakValid(account not found, account already exists, invalid amount). - The custom error
*SaldoKurangError(insufficient balance), which satisfies theerrorinterface. BankBaru,BukaAkun,Saldo, andRiwayatare already complete. Study how they use the map and wrap errors.
Task
Complete the three methods below. Every successful operation must append a Transaksi to the history of the account involved (b.riwayat[nama]). A failed operation must not change the balance or the history.
-
func (b *Bank) Setor(nama string, jumlah int) errorjumlah <= 0→ an error that wrapsErrJumlahTidakValid.- The account doesn't exist → an error that wraps
ErrAkunTidakAda(see howSaldodoes it). - Success: the balance goes up; record
Transaksi{Jenis: Setoran, Jumlah: jumlah}.
-
func (b *Bank) Tarik(nama string, jumlah int) error- Validate the amount and the account as in
Setor. - Insufficient balance → return
&SaldoKurangError{Akun: nama, Saldo: <saldo saat ini>, Diminta: jumlah}, where<saldo saat ini>is the current balance. - Success: the balance goes down; record
Transaksi{Jenis: Penarikan, Jumlah: jumlah}.
- Validate the amount and the account as in
-
func (b *Bank) Transfer(dari, ke string, jumlah int) error- Validate the amount, then both accounts must exist (
ErrAkunTidakAda). - Insufficient balance in
dari→ a*SaldoKurangErrorfor thedariaccount. - Success: move the money, record
Transaksi{Jenis: TransferKeluar, Jumlah: jumlah, Lawan: ke}in the history ofdariandTransaksi{Jenis: TransferMasuk, Jumlah: jumlah, Lawan: dari}in the history ofke.
- Validate the amount, then both accounts must exist (
The tests check the balances, the histories, and the errors: sentinel errors with errors.Is, and *SaldoKurangError through the message from its Error() method.