我正在尝试创建一个可以将给定字符串转换为给定反射类型的函数。
我正在使用cast包:
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)
}
在上面的示例中,我保持简单(它只适用于 string -> float64 转换),但在我的代码中,它也适用于所有其他原语。
我更喜欢使用这个解决方案而不是巨大而丑陋的 switch 语句,但作为一个新的 go 开发人员,我不确定是否有更好的方法。
感谢您的帮助。
慕标琳琳
相关分类