How to initialize a struct containing a slice of structs in Golang?
Example
package main
import (
"fmt"
"math/rand"
)
type LuckyNumber struct {
number int
}
type Person struct {
lucky_numbers []LuckyNumber
}
func main() {
tmp := make([]LuckyNumber, 10)
for i := range tmp {
tmp[i].number = rand.Intn(100)
}
a := Person{tmp}
fmt.Println(a)
}
{[{81} {87} {47} {59} {81} {18} {25} {40} {56} {0}]}
Most Helpful This Week
Concurrently printing array elements using goroutines and channels
How to create Slice of Struct in Golang?
How do you catch panic in Golang?
How to append struct member dynamically using Empty Interface?
Golang panic recover example
How to check specific field exist in struct?
How to convert Struct fields into Map String?
How to build a map of struct and append values to it?