bool
, int
Often in Rust programs we have bool
variables. These can be returned from a function, or from an expression evaluation.
By using a cast, we can directly convert a bool
to an i32
value. And for non-standard conversions, a match expression can be used.
There are only 2 valid boolean values in programs—true and false. Logically these are usually converted to 1 and 0.
false -> 0 true -> 1
To begin, we have an example program where we first assign some bools. And then we convert them with the simplest approach, which is an "as" cast.
bool
variables. We use an expression to set a bool
.bool
to int
occurs.bool
is now the value 0 or 1.fn main() { // Part 1: create some example bools. let result1 = true; let result2 : bool = false; let temp = 10; let result3 = temp == 10 && result1; // Part 2: convert bools to i32s. let convert1 = result1 as i32; let convert2 = result2 as i32; let convert3 = result3 as i32; // Part 3: test and print results. if convert1 == 1 { println!("TRUE IS 1"); } println!("{} = {}", result1, convert1); println!("{} = {}", result2, convert2); println!("{} = {}", result3, convert3); }TRUE IS 1 true = 1 false = 0 true = 1
Match
exampleIt is sometimes necessary to use a more complex approach to converting bools. Here we use a logic structure, match, to branch and perform the conversion.
fn main() { let result1 = true; // Use match to convert bool with more complex logic. let convert1 = match result1 { true => 10, false => 20 }; println!("{} = {}", result1, convert1); }true = 10
Converting bools to i32
values in Rust is easy to do with a cast expression. But more complex or unusual conversions can be done with a match statement as well.