๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Data Base/Go

[์‰ฝ๊ณ  ๋น ๋ฅธ Go ์‹œ์ž‘ํ•˜๊ธฐ] #2.2 Methods part Two

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 11. 2.
๋ฐ˜์‘ํ˜•

[์ถœ์ฒ˜ - 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())
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€