简体   繁体   English

如何在Rust中将布尔值转换为整数?

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

How do I convert a boolean to an integer in Rust? 如何在Rust中将布尔值转换为整数? As in, true becomes 1, and false becomes 0. 与之类似, true变为1, false变为0。

Cast it: 投放:

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

Use an if statement: 使用if语句:

if some_boolean { 1 } else { 0 }

See also: 也可以看看:

A boolean value in Rust is guaranteed to be 1 or 0 : Rust中的布尔值保证为10

The bool represents a value, which could only be either true or false . bool表示一个值,该值只能为truefalse If you cast a bool into an integer, true will be 1 and false will be 0. 如果将bool转换为整数,则true为1, false为0。

A boolean value, which is neither 0 nor 1 is undefined behavior : 既不为 0 也不为 1布尔值是未定义的行为

A value other than false ( 0 ) or true ( 1 ) in a bool. 布尔值中除false0 )或true1 )以外的其他值。

Therefore, you can just cast it to a primitive: 因此,您可以将其转换为原始类型:

assert_eq!(0, false as i32);
assert_eq!(1, true as i32);

You may use .into() : 您可以使用.into()

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

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

playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM