title: Load a YAML files with a list of items of different structs
body: <p>I have a YAML formatted like this:</p>
  <pre class="lang-yaml prettyprint-override"><code>actions:
    - type: one
      onekey: value
    - type: two
      twokey: value
      foo: bar
  </code></pre>
  <p>and I would like to load it to a Go struct. I tried using <a href="https://github.com/mitchellh/mapstructure" rel="nofollow noreferrer"><code>mapstructurs</code></a> with it's <code>DecodeHook</code> but I can't get it to work.</p>
  <p>This is what I tried:</p>
  <pre class="lang-golang prettyprint-override"><code>type Actions struct {
      actions []Action
  }
  
  type Action interface {
  }
  
  type One struct {
      Onekey string
  }
  
  type Two struct {
      Twokey string
      Foo    string
  }
  
  var actions Actions
  
  func Load() {
  ...
      config := &amp;mapstructure.DecoderConfig{
          DecodeHook: func(sourceType, destType reflect.Type, raw interface{}) (interface{}, error) {
              if fmt.Sprintf(&quot;%s&quot;, destType) == &quot;Action&quot; {
                  var result Action
  
                  switch raw.(map[string]interface{})[&quot;type&quot;] {
                  case &quot;one&quot;:
                      result = One{}
                  case &quot;two&quot;:
                      result = Two{}
                  }
                  mapstructure.Decode(raw, &amp;result)
                  return result, nil
              }
              return raw, nil
          },
          Result: &amp;actions,
      }
  ...
  }
  </code></pre>
  <p>This is ugly and doesn't work either. I get:</p>
  <pre><code>panic: interface conversion: interface {} is map[interface {}]interface {}, not map[string]interface {}
  </code></pre>
  <p>First there is:</p>
  <pre class="lang-golang prettyprint-override"><code>if fmt.Sprintf(&quot;%s&quot;, destType) == &quot;Action&quot;
  </code></pre>
  <p>which is hideous but the only way I got this part to work.</p>
  <p>Then there is to read the list item and cast it to the right struct by the <code>type</code> key. Is there a way to make this work?</p>
  <p>Thanks!</p>