Bank Account

A struct with methods that return modified copies for deposit and withdrawal.

package main

import "fmt"

type Account struct {
	Owner   string
	Balance float64
}

func (a Account) Deposit(amount float64) Account {
	a.Balance = a.Balance + amount
	return a
}

func (a Account) Withdraw(amount float64) (Account, bool) {
	if amount > a.Balance {
		return a, false
	}
	a.Balance = a.Balance - amount
	return a, true
}

func (a Account) Show() {
	fmt.Printf("%s: $%.2f\n", a.Owner, a.Balance)
}

func main() {
	acc := Account{Owner: "Alice", Balance: 100.00}
	acc.Show()

	acc = acc.Deposit(50.00)
	acc.Show()

	acc, ok := acc.Withdraw(30.00)
	if ok {
		fmt.Println("Withdrawal successful.")
	}
	acc.Show()

	acc, ok = acc.Withdraw(200.00)
	if !ok {
		fmt.Println("Insufficient funds.")
	}
	acc.Show()
}
▶ Open Go Playground

Copy the code above and paste to run

© 2026 ByteLearn.dev. Free courses for developers. · Privacy