-3

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)
5
  • 3
    Well, reflect.Int8 is a reflect.Kind, not a reflect.Type Commented Jul 24 at 15:29
  • tanks for your response, @BurakSerdar, generics is great but it may load mind a bit... Commented Jul 24 at 15:35
  • If you're already using 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.
    – Mr_Pink
    Commented Jul 24 at 15:48
  • agree, but I failed to find solution otherwise there would be no question on SO. Example here doesn't compile, the purpose is to clearly show what I'd like to achieve Commented Jul 24 at 16:24
  • For this specific case, you can parse the string as int64, and use a generic type to copy that int64 value to the target type. Commented Jul 24 at 16:48

1 Answer 1

2

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").

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.