Weird issue with if statements


#1

image

If a[2] prints out 3, how does this if statement if a[2] & y == 1 returns a true then? As you can clearly see y = 1 and a[2] = 3, they both do not equal to 1 and the if statement should return false, not true? if I type this instead a[0] & y == 1 that returns a false and it does not execute the print macro.

I am kinda confused over here.


#2

& is bitwise and, not boolean and, which is &&. That condition is (a[2] & y) == 1.


#3

What is bitwise?


#4

Bitwise operation.


#5

Note that integers do not coerce to booleans automatically in Rust. You must explicitly compare integers with 0 if you need it:

if a[2] != 0 && y == 1 {
}

#6

This is one of the reasons I wished Rust would have used and, or, and not keywords like Python for boolean operations.