0
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:

./prog.go:11:3: undefined: Text
./prog.go:11:9: cannot use "Hello" (untyped string constant) as struct{Text string; Type string} value in array or slice literal
./prog.go:12:3: undefined: Type
./prog.go:12:9: cannot use "string" (untyped string constant) as struct{Text string; Type string} value in array or slice literal

it's obvious because it is not a normal struct declaration so please help me how can I construct object of demo struct?

2
  • 1
    It's because your type is a slice of structs, but you're creating d as a single struct. Do you want the demo type to be a single struct or a slice of them? Dec 4, 2021 at 14:58
  • 2
    Don’t use a slice of anonymous structs as a type, just declare the struct you want and create a slice if you need it.
    – JimB
    Dec 4, 2021 at 15:02

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.