In Rust, a boolean is a fundamental data type used to represent logical true or false. It has only two possible values: true and false. Booleans play a central role in conditional statements, loops, and logical operations, making them one of the basics of Rust programming.
Boolean Type
Rust's boolean type is declared using the keyword bool. You can directly assign boolean literals or generate boolean values through expressions.
let is_rust_fun: bool = true;
let is_raining = false;
println!("Is Rust fun? {}", is_rust_fun);
println!("Is it raining? {}", is_raining);
// Output: Is Rust fun? true
// Output: Is it raining? false
Note: Rust is a strongly typed language; boolean values cannot be implicitly converted to integers or other types. For example, you cannot directly write if 1, but must use boolean expressions like if 1 > 0.
Boolean Operations
Rust supports standard logical operators: && (logical AND), || (logical OR), and ! (logical NOT). These operators are used to combine boolean values and are commonly used in conditional judgments. The following code demonstrates the usage of these operators.
let a = true;
let b = false;
println!("a && b: {}", a && b); // Output: false
println!("a || b: {}", a || b); // Output: true
println!("!a: {}", !a); // Output: false
These operators follow short-circuit evaluation rules: for &&, if the first operand is false, the second operand will not be evaluated; for ||, if the first operand is true, the second operand will not be evaluated.
| Operator | Description | Example |
|---|---|---|
&& |
Logical AND | true && false returns false |
|| |
Logical OR | true || false returns true |
! |
Logical NOT | !true returns false |
== |
Equal to | 5 == 5 returns true |
!= |
Not equal to | 5 != 3 returns true |
Comparison Operators Generate Boolean Values
Comparison operators such as == (equal to), != (not equal to), < (less than), > (greater than), etc., return boolean values. These are very useful in control flow. For example, checking if a number is positive.
let num = 5;
let is_positive = num > 0;
println!("Is {} positive? {}", num, is_positive);
// Output: Is 5 positive? true
Note: In Rust, comparison operators require operands to be of the same type. For example, you cannot directly compare an integer and a floating-point number; you must perform type conversion first.
Application of Boolean Values in Control Flow
Boolean values are commonly used in if statements, while loops, and match expressions.
let mut count = 0;
let mut continue_loop = true;
while continue_loop {
count += 1;
println!("Count: {}", count);
if count >= 3 {
continue_loop = false;
}
}
// Output: Count: 1
// Output: Count: 2
// Output: Count: 3
For specific usage of if, while, and match, please refer to the relevant chapters.