2015-12-15 22:12
浏览 425


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.

图片转代码服务由CSDN问答提供 功能建议


  reflect.Value  .convert:字符串类型的值不能转换为int 
goroutine 6 


   param:=“ 1” //键入字符串
ps:= fn.In(i)//键入int 
 fmt.Print(  “无法转换参数。
convertedParam:= reflect.ValueOf(param).Convert(ps)

我可以以某种方式执行此操作而无需创建开关/大小写和多行代码以转换为每种类型吗? 我只是在寻找实现此目的的最简单/最佳方法。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanguanye4124 2015-12-15 22:19

    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.

    解决 无用
    打赏 举报
  • dqiz20794 2017-11-27 14:51

    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
            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

    解决 无用
    打赏 举报

相关推荐 更多相似问题