본문 바로가기
Go

Exercise1-(1) : Struct & Constructor (feat. expert&private)

by HMangoo 2022. 2. 9.
// 만약 go.mod file not found in current directory or any parent directory; see 'go help modules'와 같은 에러 발생시 
//cmd창에 go env -w GO111MODULE = auto (window 기준)

 

# banking.go

package banking

// Go lint : 코드의 퀄리티를 올리기 위해 도움을 주는 것
// => 무엇인가 expert하려면 comment를 남겨야한다.
// 이때, variable name이 앞에 포함되어야함.

// expert를 하기 위해 모든 변수의 첫글자는 대문자
// Account struct
type Account struct {
    Owner   string
    Balance int
}
 
#main.go
package main

import (
    "fmt"

    "./banking"
)

func main() {
    account := banking.Account{Owner:"mangoo", Balance: 1000}
    fmt.Println(account)
    account.Owner = "theif"
    account.Owner = 61564896135645746
    // 이 방식은 누구나 Balance에 접근할 수 있음
    // => owner만 접근하도록 하려면?
   
}
 

# accounts.go

package accounts

// Account struct
type Account struct {
    owner   string
    balance int
}
// owner와 balance를 소문자로 만들어, main.go에서 접근할 수 없게됨

// python의 __init__와 같은 constructor가 존재하지 않음
// Go에서 function을 만들어 object를 return 시킴으로써 constructor를 만듬
// NewAccount creates Account
func NewAccount(owner string) *Account {
    account := Account{owner: owner, balance: 0}
    return &account // 실제 메모리는 return (복사본 X)
}
 
# main.go
 
package main

import (
    "fmt"

    "github.com/HMangoo/learngo/accounts"
    // import의 시작 path는 ./src에서 시작 (. - C:\Go의workspace)
)

func main() {
    account := accounts.NewAccount("mangoo")
    fmt.Println(account)
    // 출력결과 &{mangoo 0} => 복사본이 아닌 object임을 나타냄

    // 아래처럼 struct의 element를 바꿀 수 없음
    // account.onwer = "theif"
    // account.balance = 8619784964156
}

'Go' 카테고리의 다른 글

EXERCISE1-(3) : String method  (0) 2022.02.10
EXERCISE1-(2) : Method (feat. pointer, error)  (0) 2022.02.10
THEORY - Struct  (0) 2022.02.09
THEORY - Map  (0) 2022.02.09
THEORY - Array&Slice  (0) 2022.02.09

댓글