Rust Booleans
The `bool` type in Rust holds exactly two values, `true` or `false`, and sits at the center of every conditional and loop.
The bool Type
`bool` is one of Rust's scalar types. It occupies a single byte in memory and can only ever be `true` or `false` -- there's no notion of `0` or `1` standing in for it, and no other type converts implicitly into a `bool`.
Declaring Booleans
fn main() {
let is_registered: bool = true;
let has_paid = false;
println!("Registered: {}, paid: {}", is_registered, has_paid);
}Booleans from Comparisons
Most `bool` values in real programs aren't typed as literals -- they come from evaluating a comparison or a logical expression. Any expression using `==`, `<`, `&&`, and similar operators produces a `bool` you can store, pass around, or branch on.
Booleans as Comparison Results
fn main() {
let stock = 0;
let is_out_of_stock = stock == 0;
if is_out_of_stock {
println!("This item is currently unavailable");
} else {
println!("{} units in stock", stock);
}
}No Implicit Truthiness
Unlike languages such as JavaScript or Python, Rust does not treat integers, strings, or `Option` values as automatically truthy or falsy. An `if` condition must be a genuine `bool` expression -- writing `if some_number { ... }` is a compile error, full stop.
Booleans in Control Flow
Booleans drive every `if`, `while`, and the conditions inside iterator methods like `filter`. Because they're just values, you can also store them in variables, pass them as function arguments, or return them from functions, which is a common way to name a condition for readability.
A Boolean-Returning Function
fn is_even(n: i32) -> bool {
n % 2 == 0
}
fn main() {
for n in 1..=5 {
println!("{} is even: {}", n, is_even(n));
}
}- `bool` has exactly two values: `true` and `false`
- Comparison and logical operators are the most common source of `bool` values
- Rust has no implicit truthiness -- conditions must be genuine `bool` expressions
- Functions can return `bool` to give a condition a descriptive name, like `is_even`
Exercise: Rust Booleans
What are the only two possible values of Rust's bool type?