douhui5953 2019-01-07 13: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:

package main

import (
    "fmt"
    "reflect"
    "strings"

    "github.com/spf13/cast"
)

type functions struct{}

func (f functions) Float64(v string) float64 {
    return cast.ToFloat64(v)
}

func toTarget(v string, target reflect.Kind) interface{} {
    n := strings.Title(fmt.Sprintf("%s", target))
    method := reflect.ValueOf(functions{}).MethodByName(n)
    // Call.
    return method.Call([]reflect.Value{reflect.ValueOf(v)})[0].Interface()
}

func main() {
    originalValue := "10.0"
    floatingValue := toTarget(originalValue, reflect.Float64)

    fmt.Println(floatingValue)
}

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 13: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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题