http://play.golang.org/p/j-Y0mQzTdP个
package main
import "fmt"
type UselessStruct struct {
a int
b int
}
func main() {
mySlice := make([]*UselessStruct, 5)
for i := 0; i != 5; i++ {
mySlice = append(mySlice, &UselessStruct{})
}
fmt.Println(mySlice)
}
输出:[<nil> <nil> <nil> <nil> <nil> 0xc010035160 0xc010035170 0xc010035180 0xc010035190 0xc0100351a0]
我想做的是为5个无用的指令预先分配内存,存储为指针.如果我声明一个 struct 值片段:
mySlice := make([]UselessStruct, 5)
然后,这将创建5个空 struct -追加不会替换空 struct ,而是继续添加到片中,因此此代码的最终结果是:
http://play.golang.org/p/zBYqGVO85h个
package main
import "fmt"
type UselessStruct struct {
a int
b int
}
func main() {
mySlice := make([]UselessStruct, 5)
for i := 0; i != 5; i++ {
mySlice = append(mySlice, UselessStruct{})
}
fmt.Println(mySlice)
}
是:[{0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0} {0 0}]
What is the the go-idiomatic way to preallocate and fill slices?个