gogenerics

Generic type constraint match reflect.Type passed


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)

Solution

  • A simple solution to this would be:

    
    func Value[T constraints.Integer](value string) (T,error) {
        parsed, err := strconv.ParseInt(value, 10, 64)
            if err!=nil {
              // handle error
            }
            // Range check?
            if int64(T(parsed))!=parsed {
              // Overflow
            }
        return T(parsed),nil
    }
    

    Then you can use It as Value[int8]("123").