I'm trying to create a function that can cast a given string to the given reflect type.
I'm using the cast package:
- package main
-
- import (
- "fmt"
- "reflect"
- "strings"
-
- "github.com/spf13/cast"
- )
-
- type functions struct{}
-
- func (f functions) Float64(v string) float64 {
- return cast.ToFloat64(v)
- }
-
- func toTarget(v string, target reflect.Kind) interface{} {
- n := strings.Title(fmt.Sprintf("%s", target))
- method := reflect.ValueOf(functions{}).MethodByName(n)
- // Call.
- return method.Call([]reflect.Value{reflect.ValueOf(v)})[0].Interface()
- }
-
- func main() {
- originalValue := "10.0"
- floatingValue := toTarget(originalValue, reflect.Float64)
-
- fmt.Println(floatingValue)
- }
In the above example I'm keeping simple (it only works for string -> float64 conversion), but on my code, it will work for all the other primitives as well.
I prefer using this solution over a giant and ugly switch statement, but as a new go developer, I'm not sure if there is a better approach.
Thank you for your help.