title: What is the difference between reflect.ValueOf() and Value.Elem() in go?
body: <p>I started learning golang a couple of days ago and found <a href="https://golang.org/pkg/reflect/#ValueOf" rel="noreferrer">reflect.Valueof()</a> and <a href="https://golang.org/pkg/reflect/#Value.Elem" rel="noreferrer">Value.Elem()</a> quite confusing. What is the difference between this two function/methods and how to use them correctly?</p>
  <p>Both function/methods return a Value, and according to the go doc</p>
  <blockquote>
  <p>ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.</p>
  <p>Elem returns the value that the interface v contains or that the pointer v points to. It panics if v's Kind is not Interface or Ptr. It returns the zero Value if v is nil.</p>
  </blockquote>
  <p>I found this code from a post on stackoverflow but still don't understand when to use .Elem()</p>
  <pre class="lang-golang prettyprint-override"><code>func SetField(obj interface{}, name string, value interface{}) error {
      
      // won't work if I remove .Elem()
      structValue := reflect.ValueOf(obj).Elem()
      
      structFieldValue := structValue.FieldByName(name)
  
      if !structFieldValue.IsValid() {
          return fmt.Errorf(&quot;No such field: %s in obj&quot;, name)
      }
  
      if !structFieldValue.CanSet() {
          return fmt.Errorf(&quot;Cannot set %s field value&quot;, name)
      }
  
      structFieldType := structFieldValue.Type()
  
      // won't work either if I add .Elem() to the end
      val := reflect.ValueOf(value)
      if structFieldType != val.Type() {
  
          return fmt.Errorf(&quot;Provided value %v type %v didn't match obj field type %v&quot;,val,val.Type(),structFieldType)
      }
  
      structFieldValue.Set(val)
      return nil
  }
  </code></pre>