如何在Rust中将布尔值转换为整数?在中,true
变为1,false
变为0。
施展它:
fn main() {
println!("{}", true as i32)
}
Rust中的布尔值是guaranteed to be 1
or 0
:
bool表示一个值,该值只能为true或false。如果将bool转换为整数,则true将为1,false将为0。
一个布尔值,既不是0
也不是1
是undefined behavior:
bool中除false(0)或true(1)以外的值。
因此,您可以将其强制转换为原语:
assert_eq!(0, false as i32);
assert_eq!(1, true as i32);
使用if
声明:
if some_boolean { 1 } else { 0 }
也可以看看:
你可以使用.into()
:
let a = true;
let b: i32 = a.into();
println!("{}", b); // 1
let z: isize = false.into();
println!("{}", z); // 0