Rust — Booleans
The bool type
let is_active: bool = true;
let has_permission = false; // inferred
// lowercase only — True/TRUE are compile errors
Booleans are one byte wide and the sole type allowed in if conditions:
if is_active {
println!("running");
}
Comparisons produce them
let age = 20;
age >= 18 // true
age != 21 // true
"abc" < "abd" // true — lexicographic
(1, 2) < (1, 3) // true — tuples compare element-wise
No coercion exists: "true" is a string, 1 is not truthy. Conditions demand genuine bools:
let count = 0;
// if count { … } ❌ expected `bool`, found integer
if count > 0 { … } // ✓ explicit intent
if !name.is_empty() { … } // ✓ negation for emptiness checks
This strictness deletes JavaScript's entire falsy-value confusion table.
Logical operators
let a = true;
let b = false;
a && b // false — AND: both required
a || b // true — OR: either suffices
!a // false — NOT flips
Short-circuit evaluation:
// second condition never runs if first fails:
if connected() && send_packet() {
println!("delivered");
}
// guard pattern:
if user.is_none() || !user.as_ref().unwrap().active {
return;
}
Boolean methods
true.then(|| "value when true") // Option<bool→T> helper
true.then_some("eager value")
let flag = false;
flag.not(); // std invert (newer Rust): true
then/then_some build Options from conditions elegantly:
let discount = is_premium.then_some(0.20).unwrap_or(0.0);
Converting to/from
bool::from(1) // ❌ no From<int> — deliberate!
let b = x != 0; // explicit conversion instead ✓
b as u8 // cast: true → 1
Rust refuses numeric↔bool coercion entirely — no C-style "everything nonzero is true".
Bitwise on bools
a & b // non-short-circuit AND — evaluates both sides!
a | b // non-short-circuit OR
a ^ b // XOR
Rarely needed; note they differ from &&/|| by always evaluating both operands.
Mini Practice
- Trigger
if count {}; read the full compiler suggestion. - Build access check: logged_in && (admin || moderator).
- Demonstrate short-circuiting with two functions printing logs.
- Rewrite
if password == ""aspassword.is_empty()negation. - Use then_some to convert a bool into an Option discount.
Next: modules →
Related Topics
Frequently Asked Questions about Booleans
What is Booleans in Rust?
Booleans is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Booleans?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Booleans.
Why is Booleans important in Rust?
Booleans is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.