Is there a way to convert integers to bools in go or vice versa?
var a int = 3
var b bool = a != 0
I just dropped this into the demo box on the golang front page:
package main
import "fmt"
func main() {
var a int = 3
var b bool = a != 0
fmt.Println("Hello, 世界", b)
}
Output:
Hello, 世界 true
There are no conversions from bool
to integer types or vice versa.
Use the inequality operator to convert integers to bool
values:
b := i != 0
Use an if statement to convert a bool
to an integer type:
var i int
if b {
i = 1
}
Because the zero value for integer types is 0, the else branch shown in other answers is not necessary.
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.
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.