I have Go code that receives a reflection value and needs to work with it as a generic. To convert the parameter, I’ve gotten the following to work. Is there a more simple way to achieve the goal?
func toValue[T any](v reflect.Value) T {
v = v.Convert(reflect.TypeFor[T]())
var src any
reflect.ValueOf(&src).Elem().Set(v)
var dest T
reflect.ValueOf(&dest).Elem().Set(reflect.ValueOf(src))
return dest
}
I’m using this in a general purpose parser that lets the client use generics to produce typed output.