Rust Booleans
A boolean is the simplest type there is: it can only be true or false. In Rust it’s called bool, and you’ll use it everywhere you need to make a decision in your code.
Declaring a boolean
Section titled “Declaring a boolean”fn main() { let is_active = true; let has_error: bool = false; println!("active: {is_active}, error: {has_error}");}Rust almost always infers bool on its own from true/false, so you rarely need to write the type explicitly.
Booleans usually come from comparisons
Section titled “Booleans usually come from comparisons”You don’t often write true or false directly in real code — they usually come from comparing something:
fn main() { let age = 20; let can_vote = age >= 18; println!("Can vote: {can_vote}");}Output:
Can vote: trueUsing booleans in conditions
Section titled “Using booleans in conditions”The main job of a bool is deciding which branch of an if to run:
fn main() { let is_raining = true;
if is_raining { println!("Take an umbrella"); } else { println!("Leave it at home"); }}We cover if properly on the If…Else page — this is just a taste of why booleans matter.
boolholds exactly two values:trueorfalse.- Comparisons (
==,<,>=, …) produce booleans. - Conditions in
ifmust be a realbool— no implicit conversions from numbers or strings.
Quick check
Section titled “Quick check”Quick check
1. What type does a comparison like `age >= 18` produce?
2. In Rust, can you use an integer like `0` directly as a condition in an `if`, the way you might in some other languages?
Score: 0 / 2