title: How do I set a dynamic struct field in Go?
body: <p>I'm unmarshalling JSON in Go to a <code>map[string]interface{}</code> and using the interface's mixed string, float and slice values to populate field values of a <code>PlaceNode</code> struct. </p>
  
  <p>I need something like "Default values" because not all JSON objects have all Struct fields. Coming from other language backgrounds, were Structs indexable I'd be used to doing something like this to set a value on the <code>n Placenode</code> variable (e.g. as if it were a <code>self</code> or <code>this</code> keyword in JavaScript).</p>
  
  <pre><code>n[key] = value;
  </code></pre>
  
  <p>Instead, I have a method on my <code>PlaceNode</code> struct to read the <code>interface{}</code>, use <code>reflect</code> and optionally assign a value if the field can be set. My <code>interfaces{}</code> don't implement all values and so I'm having trouble unmarshmaling directly into my struct.</p>
  
  <p>Apparently none of the fields pass this <code>s.CanSet()</code> check. So I must be going about this wrong.</p>
  
  <p>How do I set a dynamic struct field in Go? </p>
  
  <pre><code>func (n PlaceNode) New(data map[string]interface{}) PlaceNode {
      for key, val := range data {
          n.Id = key
          for k, v := range val.(map[string]interface{}) {
              f := reflect.ValueOf(v)
              st := reflect.ValueOf(n)
              if (st.Kind() == reflect.Struct) {
                  s := st.FieldByName(k)
                  if f.Kind() == reflect.String &amp;&amp; true == s.CanSet()  {
                          s.SetString(f.String());
                  } else if f.Kind() == reflect.Float64 &amp;&amp; true == s.CanSet() {
                          s.SetFloat(f.Float());
                  } else if f.Kind() == reflect.Slice &amp;&amp; true == s.CanSet() {
                          s.Set(f.Slice(0, f.Len()));
                  }
              }
          }
      }
      return n
  }
  </code></pre>
  
  <p>The <code>data</code> argument <code>map[string]interface{}</code> has an interface that is also a <code>map[string]interface{}</code> and looks like this:</p>
  
  <pre><code>  {
     "XV.12A": {
      "Area": 1189.132667,
      "CensusBlock": 2032,
      "CensusBlockGroup": 2,
      "CensusCbsaFips": 40900,
      "CensusCountyFips": 61,
      "CensusMcdFips": 90160,
      "CensusMsaFips": 6922,
      "CensusPlaceFips": 3204,
      "CensusStateFips": 6,
      "CensusTract": 203,
      "CensusYear": 2010,
      "Radius": 19.455402434548,
      "RegionSize": 1189.132667
     }
   }
  </code></pre>