title: Go - Traversing nested structs
body: <p>I have a complex structure of this sort:</p>
  <pre><code>type InFoo struct {
      v3 int
  }
  type Bar struct {
      v1 int
      v2 InFoo
  }
  type Foo struct {
      A int
      B string
      C Bar
  }
  </code></pre>
  <p>At runtime, this could be further deeply nested. I wrote a function below to traverse the fields as below:</p>
  <pre><code>func main() {
      f := Foo{A: 10, B: &quot;Salutations&quot;, C: Bar{v1: 10, v2: InFoo{v3: 20}}}
      fType := reflect.TypeOf(f)
      newexaminer(fType)
  }
  
  // recursive traversal
  func newexaminer(t reflect.Type) {
      for i := 0; i &lt; t.NumField(); i++ {
          f := t.Field(i)
          fmt.Println(f.Name, f.Type.Kind(), f.Type)
          if f.Type.Kind() == reflect.Struct {
              // recurse if struct
              newexaminer(f.Type)
          }
  
      }
  }
  </code></pre>
  <p>Although this works but I am not sure if there is a better/optimized way to do this. Please suggest!</p>
  <ul>
  <li>EDIT:1
  Based on comments I changed approach to:</li>
  </ul>
  <pre><code>func main() {
      f := Foo{A: 10, B: &quot;Salutations&quot;, C: Bar{v1: 10, v2: InFoo{v3: 20}}}
      jsonRes, err := json.Marshal(f)
      if err != nil {
          fmt.Println(err)
      }
  
      var iRes interface{}
  
      err = json.Unmarshal(jsonRes, &amp;iRes)
      if err != nil {
          fmt.Println(err)
      }
      res := iRes.(map[string]interface{})
  
      for _, v := range res {
  
          fmt.Println(v)
          // need to type assert v again to extract map keys/values
      }
  } 
  </code></pre>
  <p>Playground: <a href="https://play.golang.org/p/_TXrRGxpIyx" rel="nofollow noreferrer">https://play.golang.org/p/_TXrRGxpIyx</a></p>
  <p>Is this an idomatic way of traversing structs. Looks like this will still need multiple assertions and loops to get to the inner most fields. Is this an ideal approach for a parsing a complex json document or is there a better way to do this</p>