Skip to content

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

@tiyee

Description

@tiyee

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)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions