Rust boolean
Created By: chatGPT
Booleans in Rust are represented by the
bool
type, which can hold one of two values: true
or false
. They are commonly used for conditional statements and making decisions in your program. Here's a brief overview of how to work with booleans in Rust.fn main() {
let is_raining: bool = true;
let is_sunny: bool = false;
if is_raining {
println!("Don't forget your umbrella!");
} else if is_sunny {
println!("It's a beautiful day!");
} else {
println!("Have a nice day!");
}
}
You can also perform logical operations with booleans. The most common logical operators in Rust are
&&
(AND), ||
(OR), and !
(NOT). These are useful for combining Boolean conditions in your code.fn main() {
let is_weekend = true;
let is_holiday = false;
if is_weekend || is_holiday {
println!("Time to relax!");
} else {
println!("Back to work!");
}
let is_work_time = !is_weekend;
println!("Is it work time? {}", is_work_time);
}
Rust also provides a Boolean logical expression evaluation that can lead to short-circuiting. This means that in a compound condition, if the first operand is enough to determine the result, the second one will not be evaluated.
fn main() {
let a = true;
let b = false;
// Short-circuit evaluation
if a && (b || b) {
println!("This will not print.");
}
// Example of logical NOT
let is_valid = !b;
println!("Is valid? {}", is_valid);
}