为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
函数式编程 2022-07-18 15:41:48
我正在尝试编写一种将纪元时间戳转换为int64值的方法,但该方法可能会获取多种数据类型;例如int64, int, string. 我有以下代码:package mainimport (    "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: 1606800000initial type: intcasting status: falseconverted: 0initial value: 1606800000initial type: stringcasting status: falseconverted: 0我不知道它是否相关;但我使用三个版本的 golang 编译器执行代码1.13:1.14和1.15. 都有相同的输出。
查看完整描述

1 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

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)

    }

}


查看完整回答
反对 回复 2022-07-18
  • 1 回答
  • 0 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信