title: Copy or New instance of an interface
body: <p>I have a function that takes an interface and returns an interface. It would like to initialize the result to a copy of the source, then make some changes, and return the result. For example:</p>
  
  <p><a href="http://play.golang.org/p/xoITFiXHPY" rel="nofollow">Playground</a></p>
  
  <pre><code>type Something interface {
      CopySomething() Something  // I'd like to get rid of this
      SetX(x int)
  }
  
  type RealThing struct {
      x int
  }
  
  func (t *RealThing) SetX(x int) {
      t.x = x
  }
  
  func (t *RealThing) CopySomething() Something {
      newT := *t
      return &amp;newT
  }
  
  func Updated(original Something, newX int) Something {
      newThing := original.CopySomething()  // I'd like to make the copy without .CopySomething()
      newThing.SetX(newX)
      return newThing
  }
  
  func main() {
      a := &amp;RealThing{x: 1}
      b := Updated(a, 5)
      fmt.Printf("a = %v\n", a)
      fmt.Printf("b = %v\n", b)
  }
  </code></pre>
  
  <p>This works, but the <code>CopySomething()</code> method seems unnecessary (and I'd need another identical method for every interface that needs to copy things). Is there a better way to make a copy of <code>original</code> inside of <code>Updated()</code> without an extra method? Is there some more idiomatic way to achieve this?</p>
  
  <p>In the specific case I'm working on, I could get away with just instantiating a new instance of the same type as <code>original</code> (I don't really need the copy). Is the problem any simpler that way?</p>
  
  <hr>
  
  <p>Based on Evan's comment, I thought I'd give some of the other reflect-based things I've already tried:</p>
  
  <pre><code>newThing := reflect.New(reflect.TypeOf(original))
  </code></pre>
  
  <p>==>
  Compile error: type reflect.Value has no field or method SetX</p>
  
  <pre><code>newThing := reflect.New(reflect.TypeOf(original)).Interface().(Something)
  </code></pre>
  
  <p>===>
  Runtime error: interface conversion: **main.RealThing is not main.Something</p>
  
  <pre><code>newThing := reflect.Indirect(reflect.New(reflect.TypeOf(original))).Interface().(Something)
  </code></pre>
  
  <p>===>
  Runtime error: invalid memory address or nil pointer dereference</p>
  
  <p>At this point, I felt my reflect was becoming silly and stopped just whacking at it.</p>