แบบฝึกหัด Go
Bank Account in Go with Errors
A struct, pointer methods and your own error types: deposits and withdrawals that can fail safely.
สิ่งที่คุณจะได้เรียนรู้
- Methods that return error
- A custom error type
- Unexported fields
Operation → result
Deposit(50)<nil>Withdraw(500)insufficient fundsWithdraw(120)<nil>, balance 30Every 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>.
ประเด็นสำคัญ
- Deposit rejects amounts that are not positive.
- Withdraw rejects more than the balance.
- balance is unexported, so only the methods change it.
ตัวอย่าง 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ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด