Is there a way to convert integers to bools in go or vice versa?
Is there a builtin way to cast bools to integers or vice versa? I've tried normal casting, but since they use different underlying types, conversion isn't possible the classic way. I've poured over some of the specification, and I haven't found an answer yet.
Int to bool is easy, just x != 0
will do the trick. To go the other way, since Go doesn't support a ternary operator, you'd have to do:
var x int
if b {
x = 1
} else {
x = 0
}
You could of course put this in a function:
func Btoi(b bool) int {
if b {
return 1
}
return 0
}
There are so many possible boolean interpretations of integers, none of them necessarily natural, that it sort of makes sense to have to say what you mean.
In my experience (YMMV), you don't have to do this often if you're writing good code. It's appealing sometimes to be able to write a mathematical expression based on a boolean, but your maintainers will thank you for avoiding it.
Here's a trick to convert from int
to bool
:
x := 0
newBool := x != 0 // returns false
where x
is the int
variable you want to convert from.