본문 바로가기
SW LAB/Go Lang

[Google Go 언어] 미니 프로젝트 : Banking

by 프롬스 2021. 11. 16.
반응형

Step 1

Account 를 생성하는 모듈을 만들고, Main 에서 호출해보자. Account 의 경우 func 를 이용하여 생성하자

  • `accounts.go`
package accounts

// 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
}
  • `main.go`
package main

import (
	"fmt"
	"kjham/learngo_banking/accounts"
)

func main() {
	account := accounts.NewAccount("kjham")
	fmt.Println(*account)
}

Step 2

  • 입금, 인출 func 를 Receiver 를 이용하여 만들어 보자
  • 인출 시 돈이 부족하면 Error 를 발생시키고 이를 체크해보자
  • 사전 정의 func인 String() 을 수정해보자
  • `accounts.go`
package accounts

import (
	"errors"
	"fmt"
)

// Account Struct
type Account struct {
	owner   string
	balance int
}

var errNoMoney = errors.New("Can't widthdraw")

// NewAccount creates Account
func NewAccount(owner string) *Account {
	account := Account{owner: owner, balance: 0}
	return &account
}

// Deposit x amount on your account
// (a *Account) 를 Receiver 라고 함. (a Account) 일 경우 복사본을 만들어서 값이 바뀌지 않음.
func (a *Account) Deposit(amount int) {
	a.balance += amount
}

// Balance of your account
func (a Account) Balance() int {
	return a.balance
}

// Widthdraw x amount from your account
func (a *Account) Widthdraw(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 the account
func (a Account) Owner() string {
	return a.owner
}

func (a Account) String() string {
	return fmt.Sprint(a.Owner(), "'s account.\nHas: ", a.Balance())
}
  • `main.go`
package main

import (
	"fmt"
	"kjham/learngo_banking/accounts"
	"log"
)

func main() {
	account := accounts.NewAccount("kjham")
	account.Deposit(10)
	if err := account.Widthdraw(20); err != nil {
		log.Println(err)
	}
	fmt.Println(account)
}
반응형

댓글