title: Is there a way to have json.Unmarshal() select struct type based on "type" property?
body: <p>I have some JSON of the form:</p>
  
  <pre><code>[{
      "type": "car",
      "color": "red",
      "hp": 85,
      "doors": 4
  }, {
      "type": "plane",
      "color": "blue",
      "engines": 3
  }]
  </code></pre>
  
  <p>I have types <code>car</code> and <code>plane</code> that satisfy a vehicle interface; I'd like to be able to write:</p>
  
  <pre><code>var v []vehicle
  e := json.Unmarshal(myJSON, &amp;v)
  </code></pre>
  
  <p>... and have JSON fill my slice of vehicles with a car and a plane; instead (and unsurprisingly) I just get "cannot unmarshal object into Go value of type main.vehicle".</p>
  
  <p>For reference, here are suitable definitions of the types involved:</p>
  
  <pre><code>type vehicle interface {
      vehicle()
  }
  
  type car struct {
      Type  string
      Color string
      HP    int
      Doors int
  }
  
  func (car) vehicle() { return }
  
  type plane struct {
      Type    string
      Color   string
      Engines int
  }
  
  func (plane) vehicle() { return }
  
  var _ vehicle = (*car)(nil)
  var _ vehicle = (*plane)(nil)
  </code></pre>
  
  <p>(Note that I'm actually totally uninterested in the <code>t</code> field on <code>car</code> and <code>plane</code> - it could be omitted because this information will, if someone successfully answers this question, be implicit in the dynamic type of the objects in <code>v</code>.)</p>
  
  <p>Is there a way to have the JSON umarhsaller choose which type to use based on some part of the contents (in this case, the type field) of the data being decoded?</p>
  
  <p>(Note that this is <strong>not</strong> a duplicate of <a href="https://stackoverflow.com/questions/33436730/unmarshal-json-with-unknown-fields">Unmarshal JSON with unknown fields</a> because I want each item in the slice to have a different dynamic type, and from the value of the 'type' property I know <em>exactly</em> what fields to expect—I just don't know how to tell json.Unmarshal how to map 'type' property values onto Go types.)</p>