Warm tip: This article is reproduced from serverfault.com, please click

Convert interface to int64 does not work as expected

发布于 2020-12-02 01:04:17

I am trying to write a method to convert epoch timestamps to int64 values, but the method may get multiple data types; e.g. int64, int, string. I have following piece of code for it:

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)

}

I expect it to successfully convert both t and tStr variables to int64; but, here's the result:

initial value: 1606800000
initial type: int
casting status: false
converted: 0
initial value: 1606800000
initial type: string
casting status: false
converted: 0

I don't know if it's related or not; but I executed the code with three version of golang compiler: 1.13, 1.14 and 1.15. All had same output.

Questioner
Zeinab Abbasimazar
Viewed
0
neery 2020-12-02 10:16:27

Go does not have the requested feature. Write some code like this:

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