Description
It's moderately common in any programming language to write code like (from compress/bzip2/huffman.go):
if pairs[i].length < pairs[j].length {
return true
}
if pairs[i].length > pairs[j].length {
return false
}
Perl has a special operator for this kind of code: <=>
, known as the spaceship operator. The spaceship operator is also available in C++20, Ruby, and PHP.
In Go, the new operator <=>
would be permitted for any two values a
and b
. It would follow the same type rules as for any ordered comparison. The expression a <=> b
would evaluate to an untyped integer value. The value would be -1
if a < b
, 1
if a > b
, and 0
if a == b
. For code like the above it would be used as
if cmp := pairs[i].length <=> pairs[j].length; cmp < 0 {
return true
} else if cmp > 0 {
return false
}
or as
switch pairs[i].length <=> pairs[j].length {
case -1:
return true
case 1:
return false
}
The operator lets code capture all aspects of a comparison in a single expression. The cost is that in the typical case additional comparisons are required to use the result, but those additional comparisons are simpler, and the code is easier to read because there is no need to verify that the different comparisons are using exactly the same values.