fix ToBoolE float64,float32,int,int64,int32,int16,int8,uint,uint64,uint32,uint16,uint8

This commit is contained in:
zigitn 2020-08-31 00:46:22 +08:00
parent 8d17101741
commit a9d3c95d6d
2 changed files with 71 additions and 4 deletions

View File

@ -1123,7 +1123,6 @@ func TestToBoolE(t *testing.T) {
expect bool
iserr bool
}{
{0, false, false},
{nil, false, false},
{"false", false, false},
{"FALSE", false, false},
@ -1137,10 +1136,35 @@ func TestToBoolE(t *testing.T) {
{"True", true, false},
{"t", true, false},
{"T", true, false},
{1, true, false},
{true, true, false},
{-1, true, false},
{float64(1), true, false},
{float32(1), true, false},
{int(1), true, false},
{int64(1), true, false},
{int32(1), true, false},
{int16(1), true, false},
{int8(1), true, false},
{uint(1), true, false},
{uint64(1), true, false},
{uint32(1), true, false},
{uint16(1), true, false},
{uint8(1), true, false},
{float64(0), false, false},
{float32(0), false, false},
{int(0), false, false},
{int64(0), false, false},
{int32(0), false, false},
{int16(0), false, false},
{int8(0), false, false},
{uint(0), false, false},
{uint64(0), false, false},
{uint32(0), false, false},
{uint16(0), false, false},
{uint8(0), false, false},
// errors
{"test", false, true},
{testing.T{}, false, true},

View File

@ -78,17 +78,60 @@ func ToBoolE(i interface{}) (bool, error) {
case bool:
return b, nil
case nil:
return false, nil
case float64:
if i.(float64) != 0 {
return true, nil
}
case float32:
if i.(float32) != 0 {
return true, nil
}
case int:
if i.(int) != 0 {
return true, nil
}
return false, nil
case int64:
if i.(int64) != 0 {
return true, nil
}
case int32:
if i.(int32) != 0 {
return true, nil
}
case int16:
if i.(int16) != 0 {
return true, nil
}
case int8:
if i.(int8) != 0 {
return true, nil
}
case uint:
if i.(uint) != 0 {
return true, nil
}
case uint64:
if i.(uint64) != 0 {
return true, nil
}
case uint32:
if i.(uint32) != 0 {
return true, nil
}
case uint16:
if i.(uint16) != 0 {
return true, nil
}
case uint8:
if i.(uint8) != 0 {
return true, nil
}
case string:
return strconv.ParseBool(i.(string))
default:
return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
}
return false, nil
}
// ToFloat64E casts an interface to a float64 type.