将接口转换为 int64 无法按预期工作

我正在尝试编写一种将纪元时间戳转换为int64值的方法,但该方法可能会获取多种数据类型;例如int64, int, string. 我有以下代码:


package main


import (

    "fmt"

)


func test(t interface{}) {

    tInt64, ok := t.(int64)

    fmt.Println("initial value:", t)

    fmt.Printf("initial type: %T\n", t)

    fmt.Println("casting status:", ok)

    fmt.Println("converted:", tInt64)

}


func main() {

    t := 1606800000

    tStr := "1606800000"


    test(t)

    test(tStr)


}

我希望它能够成功地将t和tStr变量转换为int64; 但是,结果如下:


initial value: 1606800000

initial type: int

casting status: false

converted: 0

initial value: 1606800000

initial type: string

casting status: false

converted: 0

我不知道它是否相关;但我使用三个版本的 golang 编译器执行代码1.13:1.14和1.15. 都有相同的输出。


函数式编程
浏览 136回答 1
1回答

慕工程0101907

Go 没有要求的功能。写一些这样的代码:func test(t interface{}) (int64, error) {    switch t := t.(type) {   // This is a type switch.    case int64:        return t, nil        // All done if we got an int64.    case int:        return int64(t), nil // This uses a conversion from int to int64    case string:        return strconv.ParseInt(t, 10, 64)    default:        return 0, fmt.Errorf("type %T not supported", t)    }}
打开App,查看更多内容
随时随地看视频慕课网APP