47

How do I convert a boolean to an integer in Rust? As in, true becomes 1, and false becomes 0.

2
  • 2
    @Stargateur I was printing them to the screen for debugging, and printing out 1s and 0s was more handy in my case than true and false. Commented Apr 2, 2019 at 5:31
  • 3
    Sometimes useful in arithmetic e.g. pub fn calculateprice(num : i32) -> i32 { return ((num > 40) as i32 * num) + num; } Commented Apr 30, 2019 at 6:22

4 Answers 4

68

Cast it:

fn main() { println!("{}", true as i32) } 
Sign up to request clarification or add additional context in comments.

4 Comments

Works, but this is too C++. Even Java would complain about this, and Rust should too, in my opinion.
@ChrisVilches why?
@Newbyte A true is a 1 only from a hardware point of view (and we can only assume non-exotic hardware), but not from a conceptual point of view. Which is fine, since it's a valid way to model it. In Java, 1 and true are two different concepts.
@ChrisVilches a bool having a value other than 0 or 1 is considered undefined behaviour: doc.rust-lang.org/reference/behavior-considered-undefined.html
43

A boolean value in Rust is guaranteed to be 1 or 0:

The bool represents a value, which could only be either true or false. If you cast a bool into an integer, true will be 1 and false will be 0.

A boolean value, which is neither 0 nor 1 is undefined behavior:

A value other than false (0) or true (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); 

Comments

23

Use an if statement:

if some_boolean { 1 } else { 0 } 

See also:

6 Comments

A simple benchmark shows that this is 20% faster than the other answers.
@Stein I think your link is outdated.
@Stein Current nightly appears to generate identical code for is_some_as and is_some_if: rust.godbolt.org/z/edcKef.
@SolomonUcko Not quite, it seems. The benchmarks still report the same difference today (regardless of names and place in file, which could influence alignment). When I swap the -O in your very useful godbolt link with the -C opt-level=3 that cargo bench feeds, it does report a difference in assembly.
Rust issue #95522 (possibly an LLVM issue) suggests this is not the best way to write it, in the rare case performance matters extremely. Contrary to that, the option_cardinality part of a simple microbenchmark suggests it is faster, with most Rust builds, but I believe that benchmark misrepresents bool-to-integer conversion because it basically checks if pointer != null { 1 } else { 0 }, which should branch anyway.
|
16

You may use .into():

let a = true; let b: i32 = a.into(); println!("{}", b); // 1 let z: isize = false.into(); println!("{}", z); // 0 

playground

1 Comment

Or from: i32::from(b).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.