dsafyx8454
2015-12-15 22:12
浏览 425
已采纳

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

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 
 
if!reflect.TypeOf(param).ConvertibleTo(ps){
 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
        default:
            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

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题