How do I convert a boolean to an integer in Rust?
Use an if
statement:
if some_boolean { 1 } else { 0 }
See also:
- How can I port C++ code that uses the ternary operator to Rust?
A boolean value in Rust is guaranteed to be 1
or 0
:
The
bool
represents a value, which could only be eithertrue
orfalse
. If you cast abool
into an integer,true
will be 1 andfalse
will 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);
You may use .into()
:
let a = true;
let b: i32 = a.into();
println!("{}", b); // 1
let z: isize = false.into();
println!("{}", z); // 0
playground
Cast it:
fn main() {
println!("{}", true as i32)
}