Golang

[GoLang 시작하기 7] Simple Bank - Method 연습

여니여니_ 2020. 3. 26. 00:07

 

은행의 계좌 Account는 Owner(string)와 Balance(int) 속성을 가지고 있는 객체이다. 

 

계좌에 Deposit(입금)하거나 Withdraw(출금)할 수 있다. 

 

속성을 public으로 하여 바로 접근하면 외부에서 임의로 조정 가능하므로

 

Deposit, Withdraw과 같은 함수를 만들어 접근하도록 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main
 
import (
    "fmt"
    "projects_yooyeon/src/accounts"
)
 
func main() {
 
    account := accounts.NewAccount("yooyeon")
 
    account.Deposit(100)
    fmt.Println(account.Balance())
 
    err := account.Withdraw(10)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(account)
 
}
 
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
}
 
func (a *Account) Deposit(amount int) {
    fmt.Println("Deposit:", amount)
    a.balance += amount
}
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
}
 
func (a Account) Owner() string {
    if a.owner == "" {
        return ""
    }
    return a.owner
 
}
 
func (a Account) String() string {
    return fmt.Sprint(a.Owner(), "'s account.\nHas: ", a.Balance())
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter

 

Withdraw 함수에서처럼 balnce 속성에 대해 존재여부(?)를 확인해야 하는 것 같다. try - catch문 같은 역할을 하는 것이 없어 직접 오류를 확인해야한다. 언제 오류가 나는지 아직 잘 이해하지 못한 부분이다. Owner 함수에서도 a.owner를 확인해 주었듯 이런 작업을 하지 않으면 오류가 난다. 

마지막의 String() 함수는 파이썬의 __str__과 같은 역할을 한다. 클래스를 출력하면 원하는대로 설정하여 출력할 수 있다. 

 

(결과)