본문 바로가기

Programming Language/Go

[Go] Go언어 튜토리얼_간단한 프로젝트생성(V1)

반응형

이번 포스팅은 간단한 프로젝트를 만들어

실행함으로써 고언어에 익숙해지기 위한 튜토리얼

 

 

 

1. 폴더 및 파일 생성

- 기본 Go path에 accounts 라는 폴더를 생성한다.

$ mkdir accounts

- 해당 폴더 안쪽에 accounts.go 파일을 생성한다

 

 

2. accounts.go 파일 작성

package accounts

//Account struct
//Func는 대문자로 시작해서 외부에서 접근이 가능하나, 안에 값들은 소문자로 시작하기 때문에 export 불가능
type Accounts struct {
    owner string
    balance int
}


//error를 관리하기 위해 변수를 선언해서 return 시킴
var errNoMoney = errors.New("Can't withdraw")


//아래와 같은 코드를 Receiver라고 함
//아래와 같이 작성하면 account는 Deposit func를 가지게 됨
//a의 타입은 Account
//receiver의 이름을 정할 때는 struct의 첫글자의 소문자로 지어야 함
//아래에서 receiver를 선언 할 때 Account가 아닌 *Account를 쓰면 복사본이 아닌 Deposit method를 호출한 Account를 사용하라는 뜻
func (a *Account) Deposit(amount int) {
    a.balance += amount
}


//balance만 출력하는 func
func (a Account) Balance() int {
    return a.balance
}


//에러를 핸들링할 수 있는 func 생성
func (a *Account) Withraw(amount int) error {
    if a.balance < amount {
        return errNoMoney
    }
    a.balance -= amount
    return nil
}


//아래에서 *Account는 Account를 pointer하고 있다는 뜻
//NewAccount : 새로운 계좌를 생성하는 func
func NewAccount(owner string) *Account {
    account := Account{owner: owner, balance: 0}
    return &account
}

>> 이렇게 accounts.go 파일 생성 완료

 

type Account struct

- 사용하고자 하는 struct 선언

- 함수이름의 첫 알파벳의 대, 소문자로 private, public func를 구분함

 

var errNoMoney

- 에러를 관리하기 위한 변수 선언

- 위와 같이 에러를 미리 선언 해놓고 불러서 사용하면 관리하기 쉽다

 

func (a *Account) Withdraw (amount int)

-struct의 func생성 : receiver

- func 뒤에 receiver를 선언함으로서 struct의 func를 가지게 됨

- struct에 *를 붙여서 *struct라고 작성하면, 복사본이 아닌 func를 호출한 struct를 사용하라는 뜻(속도향상)

- receiver의 변수 이름은 첫 알파벳의 소문자로 지어야함

 

func NewAccount (owner string) *Account

- func에서 리턴하는 것은 복사본이 아닌 object

- &, * 를 사용하는 이유는 속도가 느려지게 하지 않기 위함이다.

 

 

>> 결론적으로, 핵심은

1. method : 여기서 (a Account)는 receiver로써 method와 동등한 관계에 있다.

2. go에는 exception이 없다, error handling에 대해 배워야함

3. error에는 return의 종류가 2가지가 있다 ( error 와 nil =none )

4. go는 에러를 다루지 않고, 발생하면 넘어간다. 따라서 에러를 확인하기 위해서는 직접 코드를 추가해야함

- log.Fatalln() : Println()를 호출하고 프로그램 종료

- fmt.Println() : 단순히 에러문구 출력

 

 

3. 실행을 위한 main.go 파일 생성

package main

import (
        "fmt"
        "/learngo/accounts"
        )


func main() {
    account := accounts.NewAccount("test")
    fmt.Println(account.Balance())
    res := account.Withdraw(5)
    if res != nil {
    	fmt.Println(res)
    }
    account.Deposit(20)
    fmt.Println(account.Balance())
    res2 := account.Withdraw(10)
    if res2 != nil {
    	fmt.Println(res2)
    }
    fmt.Println(account.Balance())
}

>> 위에서 생성한 모든 함수를 실행하고 에러를 확인하는 main.go

>> 최종 출력은 아래와 같다

 

 

반응형