Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reflection 将reflect.Value从字符串转换为int_Reflection_Go - Fatal编程技术网

Reflection 将reflect.Value从字符串转换为int

Reflection 将reflect.Value从字符串转换为int,reflection,go,Reflection,Go,我犯了这样的错误 reflect.Value.Convert: value of type string cannot be converted to type int goroutine 6 当我运行此代码时 param := "1" // type string ps := fn.In(i) // type int if !reflect.TypeOf(param).ConvertibleTo(ps) { fmt.Print("Could not convert paramete

我犯了这样的错误

reflect.Value.Convert: value of type string cannot be converted to type int
goroutine 6
当我运行此代码时

param := "1" // type string
ps := fn.In(i) // type int

if !reflect.TypeOf(param).ConvertibleTo(ps) {
    fmt.Print("Could not convert parameter.\n") // this is printed
}
convertedParam := reflect.ValueOf(param).Convert(ps)
我是否可以在不创建开关/案例和多行代码以转换为每种类型的情况下以某种方式执行此操作?
我只是在寻找最简单/最好的方法。

有具体的规则。无法将字符串转换为数值


使用包从字符串中读取数值。

您可以通过反射值使用循环切换,该值将返回reflect.value kind()以返回该值的确切类型

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\n", t) // t has type bool
    case int:
        fmt.Printf("integer %d\n", t) // t has type int
    case *bool:
        fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
    case *int:
        fmt.Printf("pointer to integer %d\n", *t) // t has type *int
    default:
        fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
    }
}
v:=reflect.ValueOf(s接口{})
对于t:=0;i

要将接口中的某个类型转换为另一个类型,请首先在变量中获取该类型的值,然后使用类型转换转换值

这是正确的答案。此外,如果您想查看哪些转换可用,请查看
Convert()
函数实现:
https://golang.org/src/reflect/value.go?s=63892:63928#L2164
如果您不知道该对象将是什么类型,并且希望在运行时决定如何处理它,则需要一个开关。这从根本上说是不可避免的。话虽如此,你的问题让我困惑,因为你想要转换的东西就是不能。唯一可以转换为整数的字符串是数字字符串,如
“24”
,JimB建议使用的包中提供了C中的常见方法。我更新了问题,它是一个数字字符串,那么可能吗?是的。我建议使用
strconv
而不是
reflect
。您可能只想执行
myInt,err:=strconv.ParseInt(param,10,64)
,然后检查错误。如果字符串不是数值,
err
将为非nil,如果是,则
myInt
将保留该值。至少如果您希望输入是数字字符串。这不是处理任何输入的好方法,因为仍然需要switch语句。