Skip to content

proposal: cmp: add CompareBool #61643

Closed
Closed
@dsnet

Description

@dsnet

We just did a migration switching over usages of slices.SortFunc from func(T, T) bool to func(T, T) int and noticed that many comparisons between booleans suddenly became more complex.

Given that cmp.Compare can't be used on bools because bools are not ordered, I propose the addition of:

// CompareBool returns
//
//	-1 if x is less than y,
//	 0 if x equals y,
//	+1 if x is greater than y,
//
// where false is ordered before true.
func CompareBool[T ~bool](x, y T) int {
	switch {
	case x == false && y == true:
		return -1
	case x == true && y == false:
		return +1
	default:
		return 0
	}
}

Alternatively, we could add a helper function that converts false to 0 and true to 1.

\cc @bradfitz @danderson

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions