Home
Rust
Convert Bool to Int
This page was last reviewed on Jun 9, 2021.
Dot Net Perls
Convert bool, int. Often in Rust programs we have bool variables. These can be returned from a function, or from an expression evaluation.
I32 result. 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.
Required input, output. 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
Example code. 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.
Part 1 We create some example bools and use 3 different bool variables. We use an expression to set a bool.
Part 2 This is the important part, where the actual conversion from bool to int occurs.
Part 3 We test and print our results. We find that each 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 example. It 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.
match
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
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 9, 2021 (new).
Home
Changes
© 2007-2024 Sam Allen.