How do I convert a boolean to an integer in Rust?

爷,独闯天下 提交于 2020-02-03 05:45:27

问题


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


回答1:


Cast it:

fn main() {
    println!("{}", true as i32)
}



回答2:


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);



回答3:


Use an if statement:

if some_boolean { 1 } else { 0 }

See also:

  • How can I port C++ code that uses the ternary operator to Rust?



回答4:


You may use .into():

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

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

playground



来源:https://stackoverflow.com/questions/55461617/how-do-i-convert-a-boolean-to-an-integer-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!