Home > OS >  How do I make an object of a slice struct?
How do I make an object of a slice struct?

Time:12-05

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?

CodePudding user response:

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: "string",
    }}

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

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

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

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

Playground: https://go.dev/play/p/mQ7s4TiWCIC

  •  Tags:  
  • go
  • Related