How to create Slice of Struct in Golang?
Example
package main
import (
"fmt"
)
type Widget struct {
id int
attrs []string
}
func main() {
widgets := []Widget{
Widget{
id: 10,
attrs: []string{"blah", "foo"},
},
Widget{
id: 11,
attrs: []string{"foo", "bar"},
},
Widget{
id: 12,
attrs: []string{"xyz"},
},
}
for _, j := range widgets {
fmt.Printf("%d ", j.id)
for _, y := range j.attrs {
fmt.Printf(" %s ", y)
}
fmt.Println()
}
}
10 blah foo
11 foo bar
12 xyz
Most Helpful This Week
How to convert Struct fields into Map String?
Concurrently printing array elements using goroutines and channels
How to append struct member dynamically using Empty Interface?
How to initialize a struct containing a slice of structs in Golang?
Golang panic recover example
How to build a map of struct and append values to it?
How do you catch panic in Golang?
How to check specific field exist in struct?