[英]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中的布尔值保证为1
或0
:
The
bool
represents a value, which could only be eithertrue
orfalse
.bool
表示一个值,该值只能为true
或false
。 If you cast abool
into an integer,true
will be 1 andfalse
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
) ortrue
(1
) in a bool. 布尔值中除false
(0
)或true
(1
)以外的其他值。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.