Could you please help to mercy golang compiler in the following example. I'd like to implement generalized string parser
func Value[T reflect.Type](value string, t reflect.Type) T {
switch t.Kind() {
case reflect.Int8:
parsed, _ := strconv.ParseInt(value, 10, 8)
return int8(parsed)
case reflect.Int16:
parsed, _ := strconv.ParseInt(value, 10, 16)
return int16(parsed)
default:
panic(fmt.Sprintf("%s conversion is not supported", t))
}
}
And that supposed to be used as
var int8Value int8 = Value("5", reflect.Int8)
reflect.Int8
is areflect.Kind
, not areflect.Type
reflect
, what is the goal here with the type parameter? You can already do a type switch without generics, and if you're already using reflection you've lost any compile-time type specialization anyway.