We could use type parameters in the cpy
API in a few places.
func Func[T any](fn func(T) T) Option { ... }
Func
could be parameterized on the copied type, ensuring that the copy function has the right number of parameters and that the input and output match. However, we cannot fully express the constraints on T
using 1.18 type parameters: I do not believe there is any way to indicate that T
may be an interface type but may not be a channel.
func Shallow[T any]() Option { ... }
Shallow
could also be type parameterized, passing the type to shallow copy rather than a prototype value of that type. The limitations on expressing the constraints on T
still apply.
Unlike Func
, we cannot infer a type parameter for a call to Shallow
, so we would need to provide functions with different names for pre- and post- generics versions of Go.
func Copy[T any](c *Copier, v T) T { ... }
We cannot parameterize the Copier.Copy
method, but we could provide a Copy
function that avoids the need to use a type assertion to recover the type of the new value.
Unlike the changes to Func
and Shallow
, this does arguably make the package API simpler to use:
b := copier.Copy(a).(T) // need to type assert back to the type of a
b := cpy.Copy(copier, a) // no type assertion needed