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.
let ready = true; let both = ready && 3 > 2; let label = ready.then(|| "go");
Try it
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.
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
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())evaluatesexpensive()even when the flag is false. Usethen(|| expensive())when the value is costly or has side effects.asworks one way:true as i32is 1, but1 as booldoes not compile. Writen != 0.- Compound assignment:
flag &= cond,flag |= condandflag ^= condexist (there is no&&=). - Derived traits:
boolisCopy,Eq,Ord,HashandDefault(the default isfalse). - 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. AVec<bool>uses one byte per element, not one bit; use a bitset type when memory matters. - Iterators:
iter.all(pred)anditer.any(pred)returnbooland short-circuit.