Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Primitive Types

The Rust bool type

Reference for Rust's bool type: true and false, logical and bitwise operators, short-circuiting, then and then_some, conversion to integers and parsing.

bool has exactly two values, true and false, and occupies one byte. Conditions in if, while and match guards must be bool: Rust has no truthiness, so if 1 {} or if "text" {} is a type error, and so is if opt {} for an Option.

bool supports the logical operators &&, || and !, the non-short-circuiting bitwise forms &, | and ^, comparison (false < true), and two handy methods: then and then_some, which turn a condition into an Option.

Rust
let ready = true;
let both = ready && 3 > 2;
let label = ready.then(|| "go");

Try it

Rust Operators and then_some

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust No truthiness

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
let flag: bool = true;
let neg = !flag;
let r = flag.then_some(value);
let s = flag.then(|| compute());
Operator / method Meaning
!b Logical NOT.
a && b, a || b AND / OR with short-circuit evaluation.
a & b, a | b, a ^ b Bitwise AND / OR / XOR on booleans; both operands are always evaluated.
b.then_some(v) Some(v) if b, else None; v is computed eagerly.
b.then(f) Some(f()) if b, else None; f runs only when true.
a == b, a < b Equality and ordering (false < true).
"true".parse::<bool>() Ok for exactly "true" or "false"; anything else is Err(ParseBoolError).

Usage notes

  • then_some(expensive()) evaluates expensive() even when the flag is false. Use then(|| expensive()) when the value is costly or has side effects.
  • as works one way: true as i32 is 1, but 1 as bool does not compile. Write n != 0.
  • Compound assignment: flag &= cond, flag |= cond and flag ^= cond exist (there is no &&=).
  • Derived traits: bool is Copy, Eq, Ord, Hash and Default (the default is false).
  • Prefer enums for options with meaning. fn open(path: &str, create: bool, truncate: bool) is easy to call wrongly; named enums or a builder read better.
  • matches! gives a boolean from a pattern: matches!(x, Some(n) if n > 2).
  • Size: size_of::<bool>() is 1. A Vec<bool> uses one byte per element, not one bit; use a bitset type when memory matters.
  • Iterators: iter.all(pred) and iter.any(pred) return bool and short-circuit.