Is there a way to convert integers to bools in go or vice versa?

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.

Leave a Comment