Go将reflect.Value从string转换为int

时间:2015-12-15 22:12:07

标签: 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 parameter.\n") // this is printed
}
convertedParam := reflect.ValueOf(param).Convert(ps)

我是否可以在不创建开关/案例和多行代码的情况下以某种方式执行此操作以转换为每种类型? 我只是在寻找最简单/最好的方法。

2 个答案:

答案 0 :(得分:3)

type conversion有特定规则。字符串无法转换为数字值。

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

答案 1 :(得分:0)

你可以在循环中使用switch in循环,返回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
    }
}

要将接口中的类型转换为另一种类型,首先在变量中获取它的值,然后使用类型转换来转换值