如何将一个" sub"结构附加到go中的列表中

时间:2018-03-19 00:41:01

标签: go data-structures struct

type A struct {
  B []struct {
    C string
    D []struct {
      E string
      F []struct {
        G string
      }
    }
  }
}

假设我有结构A的实例,我想 在其中附加结构D.我会尝试做类似

的事情
var a A;
...
a.B.D = append(a.B.D, ???)

??? = A.B.D

- >类型A没有方法B

??? = D

- > undefined:D

---编辑更完整的例子---

type A struct {
  B []struct {
    C string
    D hugeNestedElement
  }
}

var a A
// Goal is to create many B's
a = append(a, what_goes_here)
// or ...
a = append(a.B, what_goes_here)

1 个答案:

答案 0 :(得分:3)

由于B是一个结构片段,因此它没有直接的D属性。可能存在可变数量的B':

type A struct {
  B []struct {
    C string
    D []struct {
      E string
      F []struct {
        G string
      }
    }
  }
}

由于B是一个切片,因此下面的条目假定您要将新D附加到第一个B

A.B[0].D = append(A.B[0].D, anotherD)