How to initalize a nested list in Golang?

Issue

I have a nested struct like this:

type Project struct {               
    FolderStructure     []FolderItem 
    Description         string
}

type FolderItem struct {
    SubFolderStructure  []SubFolderItem
    Description         string
}

type SubFolderItem struct {
    SubSubFolderStructure []SubSubFolderItem
    Description           string
}

type SubSubFolderItem struct {
    Content               string
    Description           string
}

I wonder how to initalize it, otherwise invalid memory address or nil pointer dereference will be thrown out.
Thanks in advance!

Solution

The easiest way to initialize is to create multiple instances as variables & then reuse them to assign the values to the nested structures.

Here is the working example: https://go.dev/play/p/6p3VFljyqom and same below, this is just one way of doing it and feel it’s the easiest.

package main

import "fmt"

type Project struct {
    FolderStructure []FolderItem
    Description     string
}

type FolderItem struct {
    SubFolderStructure []SubFolderItem
    Description        string
}

type SubFolderItem struct {
    SubSubFolderStructure []SubSubFolderItem
    Description           string
}

type SubSubFolderItem struct {
    Content     string
    Description string
}

func main() {
    ssfi1 := SubSubFolderItem{
        "content1",
        "description1 - SubSubFolderItem",
    }
    ssfi2 := SubSubFolderItem{
        "content2",
        "description2 - SubSubFolderItem",
    }
    sfi := SubFolderItem{
        SubSubFolderStructure: []SubSubFolderItem{ssfi1, ssfi2},
        Description:           "description 1 - SubFolderItem",
    }
    fi := FolderItem{
        SubFolderStructure: []SubFolderItem{sfi, sfi},
        Description:        "description 1 - FolderItem",
    }
    p := Project{
        FolderStructure: []FolderItem{fi, fi},
        Description:     "description 1 - Project",
    }

    fmt.Println(ssfi1)
    fmt.Println(ssfi2)
    fmt.Println(sfi)
    fmt.Println(fi)
    fmt.Println(p)
}

Answered By – Kishore

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.