Rust Booleans
A boolean is the simplest type there is. It has just two possible values: true and false. In Rust the type is called bool. It is named after George Boole, a mathematician who worked out the rules of logic that every computer now relies on.
Booleans are the answers to yes or no questions. Is the light on? Has the player won? Is this number even? Programs ask questions like these all the time, and the answers decide what happens next.
fn main() {
let light_on = true;
let door_locked = false;
println!("Light on: {}", light_on);
println!("Door locked: {}", door_locked);
}Light on: true Door locked: false
Questions that give booleans
You rarely type true or false yourself. Much more often a boolean comes from a comparison. Storing the answer in a variable with a good name can make the rest of the program read almost like a sentence:
fn main() {
let temperature = 34;
let number = 18;
let is_hot = temperature > 30;
let is_even = number % 2 == 0;
println!("Hot today? {}", is_hot);
println!("Is {} even? {}", number, is_even);
}Hot today? true Is 18 even? true
A popular habit is to start boolean names with is_, has_ or can_: is_hot, has_ticket, can_vote. When you read if can_vote, you immediately know what is being checked.
No numbers pretending to be booleans
In some languages, the number 0 means false and any other number means true. Rust does not play that game. A condition must really be a bool. If you write if 1 { }, the compiler stops and says it expected a bool but found an integer. This might feel fussy, but it prevents real bugs, where a number that was meant to be a count is accidentally used as a yes or no answer.
Combining booleans
You can combine booleans with && (and), || (or) and ! (not), which we saw on the operators page:
fn main() {
let is_weekend = true;
let is_holiday = false;
let is_raining = true;
let day_off = is_weekend || is_holiday;
let go_to_park = day_off && !is_raining;
println!("Day off: {}, park: {}", day_off, go_to_park);
}Day off: true, park: false
Practice exercises
- Create a boolean
can_votethat is true when an age is 18 or more, and print it. - Check whether a year is a leap year: divisible by 4 and not by 100, or divisible by 400.
- Write
if 1 { }in a program and read the compiler's message about types.