51 lines
1.0 KiB
Go
51 lines
1.0 KiB
Go
package models
|
||
|
||
import "errors"
|
||
|
||
// Account 银行账户(公开)
|
||
type Account struct {
|
||
ID string // 账户ID(公开)
|
||
Owner string // 账户所有者(公开)
|
||
balance float64 // 余额(私有,不能直接修改)
|
||
}
|
||
|
||
// NewAccount 创建账户
|
||
func NewAccount(id, owner string) *Account {
|
||
return &Account{
|
||
ID: id,
|
||
Owner: owner,
|
||
balance: 0,
|
||
}
|
||
}
|
||
|
||
// Deposit 存款(公开方法)
|
||
func (a *Account) Deposit(amount float64) error {
|
||
if !isValidAmount(amount) {
|
||
return errors.New("金额必须大于0")
|
||
}
|
||
a.balance += amount
|
||
return nil
|
||
}
|
||
|
||
// Withdraw 取款(公开方法)
|
||
func (a *Account) Withdraw(amount float64) error {
|
||
if !isValidAmount(amount) {
|
||
return errors.New("金额必须大于0")
|
||
}
|
||
if amount > a.balance {
|
||
return errors.New("余额不足")
|
||
}
|
||
a.balance -= amount
|
||
return nil
|
||
}
|
||
|
||
// GetBalance 获取余额(公开方法)
|
||
func (a *Account) GetBalance() float64 {
|
||
return a.balance
|
||
}
|
||
|
||
// isValidAmount 验证金额(私有函数)
|
||
func isValidAmount(amount float64) bool {
|
||
return amount > 0
|
||
}
|