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

问题描述 投票:2回答:4

如何在Rust中将布尔值转换为整数?在中,true变为1,false变为0。

rust
4个回答
10
投票

施展它:

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

9
投票

Rust中的布尔值是guaranteed to be 1 or 0

bool表示一个值,该值只能为true或false。如果将bool转换为整数,则true将为1,false将为0。

一个布尔值,既不是0也不是1undefined behavior

bool中除false(0)或true(1)以外的值。

因此,您可以将其强制转换为原语:

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

6
投票

使用if声明:

if some_boolean { 1 } else { 0 }

也可以看看:


2
投票

你可以使用.into()

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

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

playground

© www.soinside.com 2019 - 2024. All rights reserved.