title: Go - recursive struct with array and losing values
body: <p>I created an Element struct that has a parent and children, created a helper func called SubElement, and a String method that iterates through all children for print:</p>
  
  <pre><code>package main
  
  import "fmt"
  
  type Element struct {
    parent *Element
    children []Element
    tag string
  }
  
  func SubElement(parent *Element, tag string) Element {
    el := Element{}
    el.parent = parent
    el.tag = tag
    parent.children = append(parent.children, el)
    return el
  }
  
  func (el Element) String() string {
    s := "&lt;" + el.tag + "&gt;"
    for _, child := range el.children {
      s += child.String()
    }
    s += "&lt;/" + el.tag + "&gt;"
    return s
  }
  
  func main() {
    root := Element{}
    root.tag = "root"
  
    a := SubElement(&amp;root, "a")
    b := SubElement(&amp;a, "b")
    SubElement(&amp;b, "c")
  
    fmt.Println(root) // prints: &lt;root&gt;&lt;a&gt;&lt;/a&gt;&lt;/root&gt;
    fmt.Println(a) // prints: &lt;a&gt;&lt;b&gt;&lt;/b&gt;&lt;/a&gt;
    // and so on
  }
  </code></pre>
  
  <p>The problem I'm experiencing is, only the first tier of children are available from the root node I choose to print. I'm sure it's related to the use of append on parent.children, but lack the understanding of how to resolve this correctly.</p>
  
  <p>To work around the issue, I changed <code>children</code> to <code>map[int]Element</code>. Then in my SubElement func, I "append" with <code>parent.children[len(parent.children)] = el</code>. Then to iterate in the correct order, the String method for-loop is <code>for i:= 0; i &lt; len(el.children); i++</code>, accessing <code>el.children[i]</code>.</p>
  
  <p>Still, I'd like to know how to do this correctly with an array. Thanks</p>