Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

布尔类型

#![allow(unused)]
fn main() {
let b: bool = true;
}
  • 布尔类型 * 或 * bool * 是一种原始数据类型,可以取两个值之一,称为 * true * 和 * false * 。

该类型的值可以使用 字面量表达式 创建,使用对应于同名值的关键字 truefalse

该类型是 语言预导入 的一部分, 名称bool

布尔类型的对象其 大小和对齐 均为 1 。

值 false 的位模式为 0x00 ,值 true 的位模式为 0x01 。布尔类型的对象具有任何其他位模式都是 未定义行为

布尔类型是各种 表达式 中许多操作数的类型:

注意

布尔类型的作用类似于但不是 枚举类型 。在实践中,这主要意味着构造函数不与类型相关联 (例如 bool::true) 。

与所有原始类型一样,布尔类型 实现特型 CloneCopySizedSendSync

注意

有关库操作,请参阅 标准库文档

布尔值的运算

当对布尔类型的操作数使用某些运算符表达式时,它们按照 布尔逻辑 的规则进行求值。

逻辑非

b!b
truefalse
falsetrue

逻辑或

aba | b
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

逻辑与

aba & b
truetruetrue
true`false“false
falsetruefalse
falsefalsefalse

逻辑异或

aba ^ b
truetruefalse
truefalsetrue
falsetruetrue
falsefalsefalse

比较

aba == b
truetruetrue
truefalsefalse
falsetruefalse
falsefalsetrue
aba > b
truetruefalse
truefalsetrue
falsetruefalse
falsefalsefalse
  • a != b!(a == b) 相同
  • a >= ba == b | a > b 相同
  • a < b!(a >= b) 相同
  • a <= ba == b | a < b 相同

位有效性

bool 的单个字节保证被初始化 (换句话说, transmute::<bool, u8>(...) 总是健全的 – 但由于某些位模式是无效的 bool ,其反向操作并不总是健全的) 。