我正在嘗試編寫一種將紀元時間戳轉換為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 編譯器執(zhí)行代碼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)
}
}
- 1 回答
- 0 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消