Go 練習問題

Bank Account in Go with Errors

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

  • 初級
  • 約5分で読めます
  • 実行できるサンプル 1 件
学べること
  • 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>.

重要なポイント

  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.

実行できる Go のサンプル

Go
コードを実行 →
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)
}
この例の実行ボタンを作成 実行結果
<nil>
insufficient funds: need 500, have 150
amount must be positive
<nil>
Ada has 30

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Generics →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ