Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

go

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.

like image 551
worr Avatar asked Dec 06 '11 00:12

worr


People also ask

Can you convert int to bool?

You cannot cast an integer to boolean in java. int is primitive type which has value within the range -2,147,483,648 to 2,147,483,647 whereas boolean has either true or false. So casting a number to boolean (true or false) doesn't makes sense and is not allowed in java.

Is bool the same as int?

Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.

Is bool more efficient than int?

Using a bool IMO reflects its use much better than using an int . In fact, before C++ and C99, C89 didn't have a Boolean type. Programmers would often typedef int Bool in order to make it clear that they were using a boolean.


1 Answers

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.

like image 164
SteveMcQwark Avatar answered Sep 21 '22 19:09

SteveMcQwark