๋ฐ์ํ
[์ถ์ฒ - Nomad Coders]
accounts/accounts.go
package accounts
import "errors"
// Account struct
type Account struct {
owner string
balance int
}
var errNoMoney = errors.New("Can't withdraw")
// NewAccount creates Account
func NewAccount(owner string) *Account {
account := Account{owner: owner, balance: 0}
return &account
}
// Deposit x amount on your account
func (a *Account) Deposit(amount int) {
a.balance += amount
}
// Balance of your account
func (a Account) Balance() int {
return a.balance
}
// Withdraw x amount from your account
func (a *Account) Withdraw(amount int) error {
if a.balance < amount {
return errNoMoney
}
a.balance -= amount
return nil
}
main.go
package main
import (
"fmt"
"github.com/serranoarevalo/learngo/accounts"
)
func main() {
account := accounts.NewAccount("nico")
account.Deposit(10)
fmt.Println(account.Balance())
err := account.Withdraw(20)
if err != nil {
fmt.Println(err)
}
fmt.Println(account.Balance())
}
๋ฐ์ํ
'Data Base > Go' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Golang] Maps (0) | 2021.11.02 |
---|---|
[Golang] range (0) | 2021.11.02 |
[์ฝ๊ณ ๋น ๋ฅธ Go ์์ํ๊ธฐ] #2.1 Methods part One (0) | 2021.11.02 |
[์ฝ๊ณ ๋น ๋ฅธ Go ์์ํ๊ธฐ] #2.0 Account + NewAccount (0) | 2021.11.02 |
[Golang] Slices (์ฌ๋ผ์ด์ค) (0) | 2021.11.01 |
๋๊ธ