package main
import (
"fmt"
accounts "go_tutorial/nomadCoder/practiceStruct/banking"
)
type person struct {
name string
age int
favFood []string
}
func main() {
account := accounts.NewAccount("taeha")
account.Deposit(10)
fmt.Println(account.Balance())
err := account.Withdraw(20)
if err != nil {
fmt.Println(err)
}
fmt.Println(account.Balance(), account.Owner())
fmt.Println(account)
}
2. banking.go
package accounts
import (
"errors"
"fmt"
)
var errNoMoney = errors.New("No money error")
// Account struct
type Account struct {
owner string
balance int
}
// 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
}
// ChangeOwner of the account
func (a *Account) ChangeOwner(newOwner string) {
a.owner = newOwner
}
// Owner of account
func (a Account) Owner() string {
return a.owner
}
func (a *Account) String() string {
return fmt.Sprint(a.Owner(), "'s account.\nHas: ", a.Balance())
}