40

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

Newbyte
  • 2,421
  • 5
  • 22
  • 45
  • 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`. – Newbyte Apr 02 '19 at 05:31
  • 3
    Sometimes useful in arithmetic e.g. `pub fn calculateprice(num : i32) -> i32 { return ((num > 40) as i32 * num) + num; }` – S. Whittaker Apr 30 '19 at 06:22

4 Answers4

58

Cast it:

fn main() {
    println!("{}", true as i32)
}
ForceBru
  • 43,482
  • 10
  • 63
  • 98
33

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);
Tim Diekmann
  • 7,755
  • 11
  • 41
  • 69
20

Use an if statement:

if some_boolean { 1 } else { 0 }

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 6
    A [simple benchmark](https://github.com/ssomers/rust_bench_quickies/tree/master/src) shows that this is 20% faster than the other answers. – Stein Sep 18 '19 at 18:17
  • @Stein I think your link is outdated. – Tim Diekmann Apr 20 '20 at 14:32
  • 1
    @Stein Current nightly appears to generate identical code for `is_some_as` and `is_some_if`: https://rust.godbolt.org/z/edcKef. – Solomon Ucko Nov 30 '20 at 04:25
  • 1
    @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. – Stein Nov 30 '20 at 12:57
  • Hmm, true, interesting! Here's a smaller example: https://rust.godbolt.org/z/7MM49d. I'm not completely sure what's up with the control flow for `is_some_if`. – Solomon Ucko Nov 30 '20 at 22:53
  • [Rust issue #95522](https://github.com/rust-lang/rust/issues/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](https://github.com/ssomers/rust_bench_quickies) 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. – Stein Apr 09 '22 at 13:06
12

You may use .into():

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

let z: isize = false.into();
println!("{}", z); // 0

playground

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
wasmup
  • 14,541
  • 6
  • 42
  • 58