英文:
initializing a struct containing a slice of structs in 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
// 我想要优化的部分开始
var tmp []LuckyNumber
for i := 0; i < count_of_lucky_nums; i++ {
tmp = append(tmp, LuckyNumber{rand.Intn(100)})
}
a := Person{tmp}
// 我想要优化的部分结束
fmt.Println(a)
}
英文:
I have a struct that I want to initialize with a slice of structs in golang, but I'm trying to figure out if there is a more efficient version of appending every newly generated struct to the slice:
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)
}
答案1
得分: 22
你可以使用make()
来分配一个“全尺寸”的切片,然后使用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
结构体的新“实例”,因为切片已经包含了它们;因为切片不是指针的切片。所以在for
循环内部,我们只需要使用由index expression tmp[i]
指定的结构体值即可。
英文:
You can use make()
to allocate the slice in "full-size", and then use a for range
to iterate over it and fill the numbers:
tmp := make([]LuckyNumber, 10)
for i := range tmp {
tmp[i].number = rand.Intn(100)
}
a := Person{tmp}
fmt.Println(a)
Try it on the Go Playground.
Note that inside the for
I did not create new "instances" of the LuckyNumber
struct, because the slice already contains them; because the slice is not a slice of pointers. So inside the for
loop all we need to do is just use the struct value designated by the index expression tmp[i]
.
答案2
得分: 5
你可以按照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
只包含已初始化的值,而不是未初始化的零值。根据你的代码,这可能会有所不同。
英文:
You can use make()
the way icza proposes, you can also use it this way:
tmp := make([]LuckyNumber, 0, countOfLuckyNums)
for i := 0; i < countOfLuckyNums; i++ {
tmp = append(tmp, LuckyNumber{rand.Intn(100)})
}
a := Person{tmp}
fmt.Println(a)
This way, you don't have to allocate memory for tmp
several times: you just do it once, when calling make. But, contrary to the version where you would call make([]LuckyNumber, countOfLuckyNums)
, here, tmp
only contains initialized values, not uninitialized, zeroed values. Depending on your code, it might make a difference or not.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论