Golang – Assigning array of structs in for each loop

Issue

I have added some snippets of sample code that shows array assignment within a foreach loop. I am not getting the SubComments in the second println so I am concerned I need to be using pointer assignment instead. Can anyone point me in right direction please?

type Comment struct {
    ID          uint       `json:"id" gorm:"primary_key"`
    ParentId    uint       `json:"parentId"`
    SubComments []Comment  `json:"subComments"`
}

func getThreadedComments(parentId uint) []models.Comment {
    var comments []models.Comment
    if err := models.DB.Where(&models.Comment{ParentId: parentId}).Find(&comments).Error; err != nil {
        return nil
    }
    for _, comment := range comments {
        comment.SubComments = getThreadedComments(comment.ParentId)
    }
    return comments
}

    // Gives me all comments
    fmt.Println(comments)
    for _, comment := range comments {
        /////////// Problem Line
        // Should I be doing pointer assignment here?
        comment.SubComments = getThreadedComments(comment.ParentId)
    }
    // But These comments don't get set
    fmt.Println(comments[0].SubComments)

Solution

comment is a temp variable, you should assign SubComments for comments[i].
For example:

for i := range comments {
    comments[i].SubComments = getThreadedComments(comment.ParentId)
}

Answered By – Wang Zhan

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.