spf13/cast

Return error result when transform digital type (except int) to bool

tiyee opened this issue · 0 comments

tiyee commented

As title said, when you transform int16, int64 or other digital type (not int) to bool, return an error result.

func try()  {
	var i int64 = 1
	fmt.Println(cast.ToBool(i)) // false
}

because cast only assert int type.

// ToBoolE casts an interface to a bool type.
func ToBoolE(i interface{}) (bool, error) {
	i = indirect(i)

	switch b := i.(type) {
	case bool:
		return b, nil
	case nil:
		return false, nil
	case int:
		if i.(int) != 0 {
			return true, nil
		}
		return false, nil
	case string:
		return strconv.ParseBool(i.(string))
	default:
		return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
	}
}