Rust Booleans
A boolean is a value that is true or false and nothing else. Comparisons produce booleans in Rust.
Only two values
A bool holds one of two values, true or false:
let is_fun = true;
let is_tasty = false;
println!("fun = {} tasty = {}", is_fun, is_tasty);You can name the type
Write bool after the name when you want to say the type out loud. Most of the time you can leave it out, as above:
let is_fun: bool = true;
println!("is_fun = {}", is_fun);Booleans come from comparisons
Most booleans are not typed by hand. They are born when you compare two values:
let age = 20;
let can_vote = age >= 18;
println!("can_vote = {}", can_vote);Combine with AND and OR
&& means AND: both sides must be true. || means OR: at least one side must be true:
let a = true;
let b = false;
println!("and = {} or = {}", a && b, a || b);Flip with NOT
The sign ! means NOT: it flips true to false, and false to true:
let vip = false;
println!("not vip = {}", !vip);Example
fn main() {
let age = 20;
let has_ticket = true;
let can_enter = age >= 18 && has_ticket;
let vip = false;
println!("enter = {} any = {}", can_enter, can_enter || vip);
println!("not vip = {}", !vip);
}Key points
- Rust checks && and || from left to right, and stops early when the answer is already clear
In this example, age is 20 and has_ticket is true. age >= 18 is true, and true && true is true, so can_enter is true. Next, can_enter || vip is true, because OR needs only one true side, and can_enter is already true. Finally, !vip flips false to true. The stop-early rule matters in real code. Take a check like index < len && items[index] == 9. The right side only runs when the left side is true. So you never read past the end of the list.
Note
Rust has no "truthy" values.
A number is never treated as true or false.
You must write the full comparison, like count > 0.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
In if index < len && items[index] == 9, what happens when index == len?