Add a ToInt64() and necessary plumbing
This commit is contained in:
parent
7c7add0129
commit
0eed3d1b35
5
cast.go
5
cast.go
@ -27,6 +27,11 @@ func ToFloat64(i interface{}) float64 {
|
||||
return v
|
||||
}
|
||||
|
||||
func ToInt64(i interface{}) int64 {
|
||||
v, _ := ToInt64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
func ToInt(i interface{}) int {
|
||||
v, _ := ToIntE(i)
|
||||
return v
|
||||
|
11
cast_test.go
11
cast_test.go
@ -23,6 +23,17 @@ func TestToInt(t *testing.T) {
|
||||
assert.Equal(t, ToInt(eight), 8)
|
||||
}
|
||||
|
||||
func TestToInt64(t *testing.T) {
|
||||
var eight interface{} = 8
|
||||
assert.Equal(t, ToInt64(int64(8)), int64(8))
|
||||
assert.Equal(t, ToInt64(8), int64(8))
|
||||
assert.Equal(t, ToInt64(8.31), int64(8))
|
||||
assert.Equal(t, ToInt64("8"), int64(8))
|
||||
assert.Equal(t, ToInt64(true), int64(1))
|
||||
assert.Equal(t, ToInt64(false), int64(0))
|
||||
assert.Equal(t, ToInt64(eight), int64(8))
|
||||
}
|
||||
|
||||
func TestToFloat64(t *testing.T) {
|
||||
var eight interface{} = 8
|
||||
assert.Equal(t, ToFloat64(8), 8.00)
|
||||
|
36
caste.go
36
caste.go
@ -111,6 +111,42 @@ func ToFloat64E(i interface{}) (float64, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// ToInt64E casts an empty interface to an int64.
|
||||
func ToInt64E(i interface{}) (int64, error) {
|
||||
i = indirect(i)
|
||||
jww.DEBUG.Println("ToInt64E called on type:", reflect.TypeOf(i))
|
||||
|
||||
switch s := i.(type) {
|
||||
case int64:
|
||||
return s, nil
|
||||
case int:
|
||||
return int64(s), nil
|
||||
case int32:
|
||||
return int64(s), nil
|
||||
case int16:
|
||||
return int64(s), nil
|
||||
case int8:
|
||||
return int64(s), nil
|
||||
case string:
|
||||
v, err := strconv.ParseInt(s, 0, 0)
|
||||
if err == nil {
|
||||
return v, nil
|
||||
}
|
||||
return 0, fmt.Errorf("Unable to Cast %#v to int64", i)
|
||||
case float64:
|
||||
return int64(s), nil
|
||||
case bool:
|
||||
if bool(s) {
|
||||
return int64(1), nil
|
||||
}
|
||||
return int64(0), nil
|
||||
case nil:
|
||||
return int64(0), nil
|
||||
default:
|
||||
return int64(0), fmt.Errorf("Unable to Cast %#v to int64", i)
|
||||
}
|
||||
}
|
||||
|
||||
// ToIntE casts an empty interface to an int.
|
||||
func ToIntE(i interface{}) (int, error) {
|
||||
i = indirect(i)
|
||||
|
Loading…
Reference in New Issue
Block a user