title: Obtaining an addressable copy of a reflect.Value
body: <p>I want to add marshalling/unmarshalling to types that I accept, in a way similar JSON custom encoding/decoding.  I have it all working great when the type implements a Marshal method (value receiver) and Unmarshal method (pointer receiver).</p>
  <p>The Unmarshal method must obviously use a pointer receiver so that the new value is saved.  I have been told that a Marshal method using a <em>pointer</em> (not value) receiver should also be allowed.  The trouble with this is I am using a reflect.Value which is not always addressable.</p>
  <p>Here's an edited extract of the code which panics:</p>
  <pre><code>  var v reflect.Value // passed in parameter
  
    t := v.Type()
    pt := reflect.TypeOf(reflect.New(t).Interface())
  
    if t.Implements(reflect.TypeOf((*Marshaler)(nil)).Elem()) {
      str, err = v.Interface().(Marshaler).MarshalXXX()
      // ... value receiver WORKS FINE
  
    } else if pt.Implements(reflect.TypeOf((*Marshaler)(nil)).Elem()) {
      str, err = v.Addr().Interface().(Marshaler).MarshalXXX()
      // ptr receiver gives PANIC value is not addressable
  
  </code></pre>
  <p>I tried creating a copy of v, but the copy is also not addressable which makes no sense to me:</p>
  <pre><code>    tmp := reflect.New(v.Type())
      tmp.Addr().Set(v)
      str, err = tmp.Interface().(Marshaler).MarshalXXX()
  </code></pre>
  <p>In case I have not explained this well <a href="https://go.dev/play/p/oAZa1IdRjzf" rel="nofollow noreferrer">here is an example on the Go Playground</a> for you to try:</p>
  <p>Also while I am here: Is there a better way to get the type of a pointer to a the type than in the assignment to <code>pt</code> above?</p>