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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.