initializing a struct containing a slice of structs in golang

huangapple go评论77阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;math/rand&quot;
)

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 &lt; 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 &lt; 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.

huangapple
  • 本文由 发表于 2017年3月3日 22:15:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/42581173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定