【问题标题】:Convert interface to int64 does not work as expected将接口转换为 int64 无法按预期工作
【发布时间】:2020-12-02 01:04:17
【问题描述】:

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

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)

}

我希望它能够成功地将ttStr 变量转换为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.131.141.15。都有相同的输出。

【问题讨论】:

    标签: go casting timestamp


    【解决方案1】:

    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)
        }
    }
    

    Run this code on the GoLango Playgroundo

    【讨论】:

    • 在@cerise-limón 说之后我做了同样的事情,我打算自己发布。但我想我现在应该批准你的。 :-)
    猜你喜欢
    • 1970-01-01
    • 2012-01-03
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多