title: Go function to create either new pointer or new value of a generic type
body: <p>I have a function which takes a generic type and should return a function that always return a pointer. I.e. if you pass it a non-pointer type it should return a pointer to that type, if you pass it a pointer type it should return the same type. I don't want to use <code>reflect.New</code> as it's a performance-critical app.</p>
  <p>I don't mind using reflection in the function that returns the factory function, however ideally not even there.</p>
  <p>This is what I'm trying to do:</p>
  <pre class="lang-golang prettyprint-override"><code>package main
  
  import (
      &quot;fmt&quot;
      &quot;reflect&quot;
  )
  
  type Ptr[T any] interface {
      *T
  }
  
  func makeNewA[T Ptr[U], U any]() any {
      return new(U)
  }
  
  func makeNewB[T any]() any {
      return new(T)
  }
  
  func makeNew[T any](v T) func() any {
      if reflect.TypeOf(v).Kind() == reflect.Ptr {
          return makeNewA[T] // &lt;-- error: T does not match *U
      } else {
          return makeNewB[T]
      }
  }
  
  type Foo struct{}
  
  func main() {
      make1 := makeNew(Foo{})
      make2 := makeNew(&amp;Foo{})
  
      // should both return &amp;Foo{}
      fmt.Println(make1())
      fmt.Println(make2())
  }
  </code></pre>