对于下面的代码,我想知道如何将大小分配给val
mystruct
结构的片段?
package main
import (
"fmt"
)
type mystruct struct {
val []int
key int
}
type mystruct2 struct {
mm []mystruct
}
func main() {
s1 := make([]mystruct, 2)
fmt.Println(s1)
}
答案 0 :(得分:1)
如果您在初始化val
结构时询问如何分配n mystruct
切片,则可以这样做:
m := mystruct{
val: make([]int, 2), // or make([]int, 0, 2)
}
您还可以提供工厂功能,例如:
func newMystruct(n int) mystruct {
return mystruct{
val: make([]int, n), // or make([]int, 0, n)
}
}
答案 1 :(得分:0)
使用循环在嵌套struct
中分配切片:
s1 := make([]mystruct, 2)
for i := range s1 {
s1[i].val = make([]int, 2) // replace 2 with whatever size you want
}