Skip to main content
The bool type in Rust is a primitive data type representing a boolean logic value that can exist in exactly one of two states: true or false.

Control Flow and Strict Evaluation

In Rust, control flow constructs such as if and while strictly require an expression that evaluates to a bool. Unlike languages such as C, JavaScript, or Python, Rust does not have “truthy” or “falsy” values. An integer, pointer, or collection cannot be implicitly evaluated as a boolean condition; it must be explicitly compared to yield a bool.

Memory Layout and Representation

In memory, a bool occupies exactly 1 byte (8 bits) and has an alignment of 1 byte. Rust guarantees its internal byte representation: false is represented as 0x00 and true is represented as 0x01. This strict representation ensures safe interoperability with C-compatible Foreign Function Interfaces (FFI).

Syntax and Initialization

A bool can be initialized using type inference or explicit type annotation.

Type Casting

Rust allows safe, unidirectional casting from a bool to integer types (e.g., u8, i32, usize) using the as keyword. true casts to 1 and false casts to 0. Casting a bool directly to floating-point types (e.g., true as f32) is invalid and results in a compiler error (E0605).
Conversely, Rust strictly prohibits casting integer types directly back to a bool. You must explicitly evaluate a condition to convert an integer to a boolean.

Operators

The bool type supports three distinct categories of operators: Short-circuiting Logical Operators: These operators evaluate the right-hand operand lazily, bypassing evaluation if the final result is already determined by the left-hand operand.
  • && (Logical AND): Evaluates the right-hand side only if the left-hand side is true.
  • || (Logical OR): Evaluates the right-hand side only if the left-hand side is false.
Unary Operator:
  • ! (Logical NOT): Inverts the boolean state immediately.
Eager Bitwise Operators: When applied to bool, bitwise operators evaluate both operands unconditionally.
  • & (Bitwise AND)
  • | (Bitwise OR)
  • ^ (Bitwise XOR)

Trait Implementations

The bool primitive implements several core standard library traits that dictate its behavior:
  • Copy and Clone: Booleans are copied by value rather than moved.
  • Default: The default value of a bool is false.
  • PartialEq and Eq: Supports strict equality comparisons.
  • PartialOrd and Ord: Booleans are totally ordered. false is mathematically less than true (false < true evaluates to true).
  • Hash: Can be safely used as keys in a HashMap or HashSet.
Tired of Poor Rust Skills? Fix That With Deep Grasping!Learn More