How to convert a string value to the correct reflect.Kind in go?
<p>Is there a generic helper method in Go to convert a <code>string</code> to the correct value based on <code>reflect.Kind</code>?</p>

<p>Or do I need to implement the switch over all kinds myself?</p>

<p>I have a value like "143" as a string and a reflect.Value with kind "UInt16" and like to convert that string value and set it into the UInt16 value of my struct.</p>

<p>My current code looks like:</p>

<pre><code>func setValueFromString(v reflect.Value, strVal string) error {
    switch v.Kind() {
    case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
        val, err := strconv.ParseInt(strVal, 0, 64)
        if err != nil {
            return err
        }
        if v.OverflowInt(val) {
            return errors.New("Int value too big: " + strVal)
        }
        v.SetInt(val)
    case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
        val, err := strconv.ParseUint(strVal, 0, 64)
        if err != nil {
            return err
        }
        if v.OverflowUint(val) {
            return errors.New("UInt value too big: " + strVal)
        }
        v.SetUint(val)
    case reflect.Float32:
        val, err := strconv.ParseFloat(strVal, 32)
        if err != nil {
            return err
        }
        v.SetFloat(val)
    case reflect.Float64:
        val, err := strconv.ParseFloat(strVal, 64)
        if err != nil {
            return err
        }
        v.SetFloat(val)
    case reflect.String:
        v.SetString(strVal)
    case reflect.Bool:
        val, err := strconv.ParseBool(strVal)
        if err != nil {
            return err
        }
        v.SetBool(val)
    default:
        return errors.New("Unsupported kind: " + v.Kind().String())
    }
    return nil
}
</code></pre>

<p>This works already, but I wonder if this is already implemented somewhere else.</p>