'How do I construct an object of a slice struct?
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?
Solution 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |