Description
In some cases, being able to do arithmetic or bitwise operations in which you can use a true-or-false value without a branch is highly appealing. It would be convenient to allow conversion of true and false to arbitrary integer types, producing the values 1 and 0 respectively. Conveniently, unless I get around to writing up my int0
proposal and convince someone that it's a good idea, every numeric type in Go can represent both of those values.
I've been told that the Go compiler is already smart enough to generate reasonable code for something like this:
int x
if cond {
x = 1
}
However, even if the compiler can do it, it's a lot more code to read than something like int(cond)
would be, and whether or not it's branchy is less obvious and I don't know whether it's safe to use this in code where a branch is Too Expensive. (Unfortunately, Google Groups has destroyed any once-functional Usenet searching, so I can't find the reference, but I seem to recall someone getting a 20% overall improvement in a PRNG by replacing if (z) { x += y }
with x += y * z
.)
I originally strongly disliked the thing where true and false weren't numeric values, but I've come to quite appreciate the need to make a conversion between booleans and numbers explicit. But "explicit" need not mean "verbose". Allowing int(a < b)
to be 1 or 0 depending on whether a was or was not (respectively) less than b seems like it would simplify a lot of code without hurting anything.