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?

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题