How do I make an object of a slice struct?

Issue

package main

import (
    "fmt"
)
type demo []struct {
    Text string
    Type string
}
func main() {
    
    d := demo{
        Text: "Hello",
        Type: "string",
    }
    
}

In this code I’m getting an error while declaring the object of demo struct, it’s obvious because it is not a normal struct declaration so please help me how can I make object of demo struct?

Solution

Since you declared demo as a slice of anonymous structs, you have to use demo{} to construct the slice and {Text: "Hello", Type: "string"} to construct the item(s).

func main() {
    d := demo{{
        Text: "Hello",
        Type: "Anon",
    }}

    fmt.Println(d)
    // [{Hello Anon}]
}

Being a slice, you can also make it, but then appending items requires replicating the definition of the anonymous struct:

func main()
    d1 := make(demo, 0)
    d1 = append(d1, struct {
        Text string
        Type string
    }{"Hello", "Append"})

    fmt.Println(d1)
    // [{Hello Append}]
}

However albeit it compiles, it is rather uncommon. Just define the named struct type, and then d as a slice of those. The syntax is almost the same, but straightforward:

// just defined struct type
type demo struct {
    Text string
    Type string
}

func main() {
    
    d2 := []demo{{
        Text: "Hello",
        Type: "Slice",
    }}
    fmt.Println(d2)
    // [{Hello Slice}]
}

Playground: https://go.dev/play/p/4kSXqYKEhst

Answered By – blackgreen

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.