I am getting an error like this
reflect.Value.Convert: value of type string cannot be converted to type int
goroutine 6
When I am running this code
param := "1" // type string
ps := fn.In(i) // type int
if !reflect.TypeOf(param).ConvertibleTo(ps) {
fmt.Print("Could not convert parameter.
") // this is printed
}
convertedParam := reflect.ValueOf(param).Convert(ps)
Can I do this in some way without creating a switch/case and multiple lines of code for converting to each type? I am just looking for the easiest/best way to do this.
There are specific rules for type conversion. Strings cannot be converted to numeric values.
Use the strconv
package to read a numeric value from a string.
You can use switch in loop through the reflect values which will return the reflect.Value kind() to return the exact type of that value
v := reflect.ValueOf(s interface{})
for t := 0; i < v.NumField(); i++ {
fmt.Println(v.Field(i)) // it will prints the value at index in interface
switch t := v.Kind() {
case bool:
fmt.Printf("boolean %t
", t) // t has type bool
case int:
fmt.Printf("integer %d
", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t
", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d
", *t) // t has type *int
default:
fmt.Printf("unexpected type %T
", t) // %T prints whatever type t has
}
}
To convert a type in interface to another type first fetch the value of it in a variable and then use type conversions to convert the value