상세 컨텐츠

본문 제목

[Go] 구조체와 errors를 이용, 은행 계좌 만들기

Go

by 경밤 2020. 2. 9. 23:57

본문

반응형

0. 앞서 들어가기전에 ...

src폴더에 accounts 폴더를 생성한후, 그 아래 accounts.go 파일을 만든다. 왜 만드냐면

accounts.go에 은행 계좌 구조체를 만들고, 그에 따른 부속 함수들을 만들 것이기 때문이다.


1. Account 구조체 만들고, 생성 함수 만들기

은행 계좌 프로그램을 작성하는데 계좌 구조체가 빠지면 안된다. 이 Account 구조체에는 Owner과 Balance가 있다.

package accounts

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

그리고 Account 구조체 인스턴스를 생성해 그 메모리 주소를 넘겨주는 NewAccount함수도 만들어 주자.

//NewAccount with zero balance and new owner
func NewAccount(owner string) *Account {
	account := Account{owner: owner, balance: 0}
	return &account //return memory address to make faster program. (same with return copy)
}

NewAccount함수가 *Account를 반환하는 이유는 저 함수에서는 인스턴스로 생성된 account가 지역변수라 함수가 끝나면 소멸되서 다른 곳에서 변경할 걱정도 없을뿐더러 account 통째로 넘겨주는, 즉 복사본을 넘겨주는 것보다 메모리 주소를 넘겨주는것이 훨씬 빠르기 때문에 *Account를 반환한다.

2. 입금과 출금함수 만들기 그 외 ...

간단하게 입금 함수와 출금함수를 만들어보도록 한다.

var errNoMoney = errors.New("You Can't Withdraw More than Balance")

//Deposit to account
func (acc *Account) Deposit(amount int) { //just get Copy of Account, so it needs pointer to revise
	acc.balance += amount
}

//Withdraw to account
func (acc *Account) Withdraw(amount int) error {
	if acc.balance < amount {
		return errNoMoney
	}
	acc.balance -= amount
	return nil
}

여기서 궁금한것이 있다. 왜 (acc '*'Account)로 포인터를 받는것일까? 답은 아주 간단하다. 저 상태에서 포인터를 받지 않고 그저 Account를 받는다면, 그것은 호출대상의 복제본을 받는것이라 balance를 직접수정하는 Deposit함수와 Withdraw함수가 아무리 해당 값을 바꾸어도 호출대상 객체에 변함이 없다. 그래서 그 호출대상객체의 메모리 포인터를 가져와서 수정하는 것이다.

새 에러를 생성하는 방법은 errors.New로 생성하면 된다 간단하다.


3. 우리가 만든 accounts 패키지를 main에서 사용하기

이것 또한 매우 쉽다. import "./accounts"를 하고, 그저 accounts.NewAccount를 이용해 새 계정을 만들수있다.

package main

import "./accounts"

func main() {
	myAccount := accounts.NewAccount("minwoo")
	myAccount.Deposit(50000)
	myAccount.Withdraw(30000)
}

 그 외에 많은 함수들을 만들어서 쓸수있다 가령 Balance함수는 account.balance를 출력해준다던지 하는 함수 말이다.

 

반응형

관련글 더보기