ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Golang] struct 리스트로 반환하기
    언어/Golang 2018. 12. 18. 23:39

    struct 성질을 까먹고 한참 삽질하다가 정리하던 도중 중요한 부분을 기억했습니다...........

    GO에서 struct를 선언하는 방식은 여러가지가 있습니다. struct 성질을 먼저 복기한 후, struct를 리스트로 반환하는 코드를 설명하겠습니다.

    1. 빈 struct 객체 먼저 생성 후 데이터 채우기

    Article이란 빈 객체를 생성 후 데이터를 삽입하는 코드입니다.

    type Article struct {
        Title      string
    }
    
    
    func main() {
    	article := Article{}
    	article.Title = "test"
    }

    2. GO 내장함수 new() 사용

    GO 내장함수인 new() 메소드를 사용하여 생성합니다.

    type Article struct {
        Title      string
    }
    
    
    func main() {
    	article := new(Article)
    	article.Title = "test"
    }


    두 방식이 동일해 보이지만 반환되는 값에 아주 큰 차이가 있습니다. 1번의 경우 value가 넘어오지만 2번은 객체의 pointer가 넘어오게 됩니다. 이 부분을 간과하고 struct 를 리스트로 하려다 혼돈에 빠졌었습니다. 

    만약 struct 객체를 생성한 다음, 다른 함수에 넘겨주는 일이 없다면 1번을 사용해도 되지만 해당 struct를 다른 함수에 넘겨 사용하는 일이 있으면 2번처럼 선언하여 사용하는 것이 좋습니다.

    struct 리스트로 반환

    struct를 리스트로 만드는 것은 아주 간단합니다. 해당 코드에 맞게 struct를 잘 선언해서 사용하면 됩니다.

    type Article struct {
        Title      string
    }
    
    // list: value, list data: value
    func InitArticleList1() []Article {
        articleList := []Article{}
        return articleList
    }
    // list: pointer, list data: value
    func InitArticleList2() *[]Article {
        articleList := []Article{}
        return &articleList
    }
    
    // list: pointer, list data: pointer
    func InitArticleList3() *[]*Article {
        articleList := []*Article{}
        return &articleList
    }
    
    func appendList1(articleList *[]Article) {
        article := Article{"test"}
        *articleList=append(*articleList, article)
    }
    
    func appendList2(articleList *[]*Article) {
        article := new(Article)
    		article.Title = "test"
        *articleList=append(*articleList, article)
    }
    
    func main() {
    
        articleList1 := InitArticleList1()
        appendList1(&articleList1)
    		articleList2 := InitArticleList2()
        appendList1(articleList2)
        articleList3 := InitArticleList3()
        appendList2(articleList3)
    
        fmt.Println(articleList1)
        fmt.Println(articleList2)
    	fmt.Println(articleList3)
    }
    
    
    // 결과
    // [{test}]
    // &[{test}]
    // &[0xc42000e1f0]


    댓글