When we defined a structure earlier, we actually extracted the common attributes (fields) and behaviors (methods) of a type of thing to form a physical model (template) . This method of studying problems is called abstraction.
After you extract the attributes and behaviors of a type of thing, the next step is to embody the code. The following is a simulated bank card deposit and withdrawal method to check the balance.
package main
import "fmt"
type Account struct {
AccountNum string
Password string
Balance float64
}
func (account *Account) Cunqian(money float64, password string) {
if account.Password != password {
fmt.Println("用户名密码错误!")
return
}
if money < 0 {
fmt.Println("输入的金额不正确!")
return
}
account.Balance += money
fmt.Println("存款成功!")
}
func (account *Account) Quqian(money float64, password string) {
if account.Password != password {
fmt.Println("用户名密码错误!")
return
}
if money < 0 || money > account.Balance {
fmt.Println("输入的金额不正确!")
return
}
account.Balance -= money
fmt.Println("取款成功!")
}
func (account *Account) Chaxunyuer(password string) {
if account.Password != password {
fmt.Println("用户名密码错误!")
return
}
fmt.Println("当前余额:", account.Balance)
}
func main() {
a := &Account{
AccountNum: "123456",
Password: "123456",
Balance: 0,
}
a.Cunqian(12.3, "123456")
a.Chaxunyuer("123456")
a.Quqian(10.2, "123456")
a.Chaxunyuer("123456")
}
存款成功!
当前余额: 12.3
取款成功!
当前余额: 2.1000000000000014