在 golang 中初始化包含一片结构的结构

initializing a struct containing a slice of structs in golang

我有一个结构,我想用 golang 中的一片结构初始化,但我想弄清楚是否有更有效的版本将每个新生成的结构附加到片中:

package main

import (
    "fmt"
    "math/rand"
)

type LuckyNumber struct {
    number int
}

type Person struct {
    lucky_numbers []LuckyNumber
}

func main() {
    count_of_lucky_nums := 10
    // START OF SECTION I WANT TO OPTIMIZE
    var tmp []LuckyNumber
    for i := 0; i < count_of_lucky_nums; i++ {
        tmp = append(tmp, LuckyNumber{rand.Intn(100)})
    }
    a := Person{tmp}
    // END OF SECTION I WANT TO OPTIMIZE
    fmt.Println(a)
}

您可以使用 make() to allocate the slice in "full-size", and then use a for range 对其进行迭代并填充数字:

tmp := make([]LuckyNumber, 10)
for i := range tmp {
    tmp[i].number = rand.Intn(100)
}
a := Person{tmp}
fmt.Println(a)

Go Playground 上试用。

请注意,在 for 内部,我没有创建 LuckyNumber 结构的新 "instances",因为切片已经包含它们;因为切片不是指针切片。所以在 for 循环中,我们需要做的就是使用 index expression tmp[i].

指定的结构值

可以按照icza建议的方式使用make(),也可以这样使用:

tmp := make([]LuckyNumber, 0, countOfLuckyNums)
for i := 0; i < countOfLuckyNums; i++ {
    tmp = append(tmp, LuckyNumber{rand.Intn(100)})
}
a := Person{tmp}
fmt.Println(a)

这样,您就不必多次为 tmp 分配内存:您只需在调用 make 时分配一次。但是,与调用 make([]LuckyNumber, countOfLuckyNums) 的版本相反,此处 tmp 仅包含初始化值,不包含未初始化的归零值。根据您的代码,它可能会有所不同。