How to convert interface to int64 in Go
Created
Modified
Type Assertion
To convert interface to int64 in Go, Using Type Assertion.
A type assertion provides access to an interface value's underlying concrete value.
package main
import "fmt"
// t := i.(T)
// t, ok := i.(T)
func main() {
var v interface{} = 1
// interface to int
i, ok := v.(int)
fmt.Println(i, ok)
// int to int64
i64 := int64(i)
s := fmt.Sprintf("Type: %T, %d", i64, i64)
fmt.Println(s)
i64 = v.(int64) // panic
}
1 true Type: int64, 1 panic: interface conversion: interface {} is int, not int64
If i does not hold a T, the statement will trigger a panic.
Type switches
A type switch is like a regular switch statement, but the cases in a type switch specify types (not values), and those values are compared against the type of the value held by the given interface value.
func i2num(i interface{}) (int64, error) {
switch v := i.(type) {
case int64:
return v, nil
case int:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
return 0, errors.New("type error")
}
}
// i, err := i2num("34")
// i, err := i2num("34.2")
// fmt.Println(i, err)
0 strconv.ParseInt: parsing "34.2": invalid syntax