Go - 02. BankAccount project
BankAccount project
package accounts
import (
"errors"
"fmt"
)
// 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 //nil = null, err no exist
}
// ChangeOnwer of the account
func (a *Account) ChangeOwner(newOwner string) {
a.owner = newOwner
}
func (a Account) Owner() string {
return a.owner
}
func (a Account) String() string {
return fmt.Sprint(a.Owner(), "'s account.\nHas: ", a.Balance())
}
package main
import (
"fmt"
"github.com/y00913/learngo/accounts"
)
func main() {
account := accounts.NewAccount("nico")
account.Deposit(10)
fmt.Println(account)
}