我有一個結構體,我想用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)
}
更有效率如何?你只是想跳過tmp變量? https://play.golang.org/p/XKg4VouoUI – JimB