Primitive Type bool1.0.0[−]
Expand description
布尔类型。
bool 代表一个值,它只能是 true 或 false。
如果将 bool 转换为整数,则 true 表示为 1,false 表示为 0。
基本用法
bool 实现了各种 traits,例如 BitAnd、BitOr、Not 等,允许我们使用 &、| 和 ! 执行布尔运算。
if 需要一个 bool 值作为它的条件。
assert! 是测试中的一个重要宏,检查表达式是否为 true,如果不是则为 panics。
let bool_val = true & false | false;
assert!(!bool_val);RunExamples
bool 用法的一个简单示例:
let praise_the_borrow_checker = true;
// 使用 `if` 有条件
if praise_the_borrow_checker {
println!("oh, yeah!");
} else {
println!("what?!!");
}
// ... 或者,匹配模式
match praise_the_borrow_checker {
true => println!("keep praising!"),
false => println!("you should praise!"),
}Run另外,由于 bool 实现了 Copy trait,因此我们不必担心移动语义 (就像整数和浮点图元一样)。
现在将 bool 强制转换为整数类型的示例:
assert_eq!(true as i32, 1);
assert_eq!(false as i32, 0);RunImplementations
Trait Implementations
执行 &= 操作。 Read more
执行 &= 操作。 Read more
执行 |= 操作。 Read more
执行 |= 操作。 Read more
执行 ^= 操作。 Read more
执行 ^= 操作。 Read more
从字符串中解析 bool。
产生 Result<bool, ParseBoolError>,因为 s 实际上可以解析,也可以不解析。
Examples
use std::str::FromStr;
assert_eq!(FromStr::from_str("true"), Ok(true));
assert_eq!(FromStr::from_str("false"), Ok(false));
assert!(<bool as FromStr>::from_str("not even a boolean").is_err());Run注意,在许多情况下,str 上的 .parse() 方法更合适。
assert_eq!("true".parse(), Ok(true));
assert_eq!("false".parse(), Ok(false));
assert!("not even a boolean".parse::<bool>().is_err());Runtype Err = ParseBoolError
type Err = ParseBoolError
可以从解析中返回的相关错误。
如果存在,则此方法返回 self 和 other 值之间的顺序。 Read more