How do I convert a boolean to an integer in Rust? As in, true becomes 1, and false becomes 0.
A boolean value in Rust is guaranteed to be 1 or 0:
The
boolrepresents a value, which could only be eithertrueorfalse. If you cast aboolinto an integer,truewill be 1 andfalsewill be 0.
A boolean value, which is neither 0 nor 1 is undefined behavior:
A value other than
false(0) ortrue(1) in a bool.
Therefore, you can just cast it to a primitive:
assert_eq!(0, false as i32);
assert_eq!(1, true as i32);