Go Practice Exercises

Bank Account in Go with Errors

A struct, pointer methods and your own error types: deposits and withdrawals that can fail safely.

  • Beginner
  • 5 min read
  • 1 runnable example
What you'll learn
  • Methods that return error
  • A custom error type
  • Unexported fields
Operation → result
Deposit(50)<nil>
Withdraw(500)insufficient funds
Withdraw(120)<nil>, balance 30

Every operation can succeed or fail

This exercise combines a struct, pointer methods and error handling. Each operation returns an error, and the error says exactly what went wrong.

Deposit rejects amounts that are not positive and Withdraw rejects an amount larger than the balance, so the balance can never become invalid. balance starts with a lower-case letter, so code outside the package cannot change it directly. A nil error prints as <nil>.

Key points

  1. Deposit rejects amounts that are not positive.
  2. Withdraw rejects more than the balance.
  3. balance is unexported, so only the methods change it.

Runnable Go example

Go
Run code →
main.go
package main

import (
	"errors"
	"fmt"
)

var ErrInvalidAmount = errors.New("amount must be positive")

type InsufficientFundsError struct {
	Needed, Available int
}

func (e InsufficientFundsError) Error() string {
	return fmt.Sprintf("insufficient funds: need %d, have %d", e.Needed, e.Available)
}

type Account struct {
	Owner   string
	balance int
}

func (a *Account) Deposit(amount int) error {
	if amount <= 0 {
		return ErrInvalidAmount
	}
	a.balance += amount
	return nil
}

func (a *Account) Withdraw(amount int) error {
	if amount > a.balance {
		return InsufficientFundsError{Needed: amount, Available: a.balance}
	}
	a.balance -= amount
	return nil
}

func main() {
	account := &Account{Owner: "Ada", balance: 100}
	fmt.Println(account.Deposit(50))
	fmt.Println(account.Withdraw(500))
	fmt.Println(account.Deposit(0))
	fmt.Println(account.Withdraw(120))
	fmt.Println(account.Owner, "has", account.balance)
}
Get a Run button for this example Result of running the code
<nil>
insufficient funds: need 500, have 150
amount must be positive
<nil>
Ada has 30

Practice

Open the example in the online compiler, change a value or add a line, and predict the output before you run it. Then break the code on purpose and read the compiler's message.

Finished this lesson?

Mark it as learned to track your progress.

Next: Generics →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges