Go lang嵌套切片大小分配

时间:2018-05-17 01:10:09

标签: go slice

对于下面的代码,我想知道如何将大小分配给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)
            }

2 个答案:

答案 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
}