Booleans
| bool values | |
| Logic operators | |
| Short-circuit | |
| Booleans in if |
bool values
The bool type holds exactly two values: true and false.
Comparisons and flags use it everywhere, from loop control to option checks.
fn main() {
let ready: bool = true;
let done = false;
println!("{} {}", ready, done);
}
cargo run
true false
Logic operators
Combine conditions with AND, OR, and NOT.
Use double ampersands for AND, double pipes for OR, and the mark for NOT.
fn main() {
let a = true && false;
let b = true || false;
let c = !true;
println!("{} {} {}", a, b, c);
}
cargo run
false true false
Short-circuit
AND and OR stop early when the answer is already known.
With false on the left of AND, the right side never runs, so the helper below stays silent.
fn is_ready() -> bool {
println!("checked");
true
}
fn main() {
let ok = false && is_ready();
println!("{}", ok);
}
cargo run
false
Booleans in if
An if condition must be a plain bool, with no implicit conversion from numbers or strings.
That rule keeps branches honest: the tested value is always exactly true or false.
fn main() {
let ready = true;
if ready {
println!("go");
} else {
println!("wait");
}
}
cargo run
go
Next: Tuples
Article author: Arthur Isaev