我正在尝试编写一种将纪元时间戳转换为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 回答
![?](http://img1.sycdn.imooc.com/533e4ce900010ae802000200-100-100.jpg)
慕工程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)
}
}
- 1 回答
- 0 关注
- 134 浏览
添加回答
举报
0/150
提交
取消