douhui5953 2019-01-07 05:11
浏览 53
已采纳

将字符串转换为其他任何原始类型的惯用方式

I'm trying to create a function that can cast a given string to the given reflect type.

I'm using the cast package:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. "github.com/spf13/cast"
  7. )
  8. type functions struct{}
  9. func (f functions) Float64(v string) float64 {
  10. return cast.ToFloat64(v)
  11. }
  12. func toTarget(v string, target reflect.Kind) interface{} {
  13. n := strings.Title(fmt.Sprintf("%s", target))
  14. method := reflect.ValueOf(functions{}).MethodByName(n)
  15. // Call.
  16. return method.Call([]reflect.Value{reflect.ValueOf(v)})[0].Interface()
  17. }
  18. func main() {
  19. originalValue := "10.0"
  20. floatingValue := toTarget(originalValue, reflect.Float64)
  21. fmt.Println(floatingValue)
  22. }

In the above example I'm keeping simple (it only works for string -> float64 conversion), but on my code, it will work for all the other primitives as well.

I prefer using this solution over a giant and ugly switch statement, but as a new go developer, I'm not sure if there is a better approach.

Thank you for your help.

展开全部

  • 写回答

1条回答 默认 最新

  • doubi1931 2019-01-07 05:50
    关注

    The "big switch" statement you want to avoid, that is already written in the standard library. Use the fmt package to easily parse primitive values from strings, specifically the fmt.Sscan() and fmt.Sscanf() functions.

    fmt.Sscan() requires a string value to parse something out from, and the address of a variable to put the parsed value into. The type of the pointed variable also determines what and how to parse out of the string. fmt.Sscan() will return the number of successfully parsed values, and an optional error (if something goes wrong).

    A simple example:

    var i int
    if _, err := fmt.Sscan("12", &i); err != nil {
        fmt.Println("Error:", err)
    }
    fmt.Println(i)
    
    var f float32
    if _, err := fmt.Sscan("12.2", &f); err != nil {
        fmt.Println("Error:", err)
    }
    fmt.Println(f)
    

    Output (try it on the Go Playground):

    12
    12.2
    

    Also note that you can parse multiple values in one step with fmt.Sscan(), for example:

    var i int
    var f float32
    
    fmt.Println(fmt.Sscan("12 12.2", &i, &f))
    fmt.Println(i, f)
    

    This will print (try it on the Go Playground):

    2 <nil>
    12 12.2
    

    The first line contains the return values of fmt.Sscan(): tells it parsed 2 values, and returned no error (nil error). The second line contains the parsed values of i and f.

    For more options, read: Convert string to integer type in Go?

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 盘古气象大模型调用(python)
  • ¥15 传人记程序做的plc 485从机程序该如何写
  • ¥15 已知手指抓握过程中掌指关节、手指各关节和指尖每一帧的坐标,用贝塞尔曲线可以拟合手指抓握的运动轨迹吗?
  • ¥50 libwebsockets 如何添加其他socket事件回调
  • ¥50 实现画布拖拽算子排布,通过flink实现算子编排计算,请提供思路
  • ¥15 esium自定义材质拉伸问题
  • ¥15 cmake+mingw使用<mysqlx/xdevapi.h>报错
  • ¥15 eNSP中防火墙的使用
  • ¥15 关于#mlnet#的问题:mlnet相关请求(语言-c#)
  • ¥15 lvgl7.11怎么做出文字被选中的效果
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部