Logical operators in Rust are used to combine or manipulate Boolean values (true or false). They play a crucial role in decision-making and control flow within programs.
Types of Logical Operators in Rust
Operator | Description | Syntax Example | Output |
---|---|---|---|
&& | Logical AND | true && false | false |
` | ` | Logical OR | |
! | Logical NOT | !true | false |
Detailed Explanation
1. Logical AND (&&)
The && operator evaluates to true only if both operands are true.
Syntax:
let result = condition1 && condition2;
Example:
fn main() {
let age = 25;
let has_id = true;
if age >= 18 && has_id {
println!("You are eligible to enter.");
} else {
println!("You are not eligible to enter.");
}
}
Output:
You are eligible to enter.
2. Logical OR (| |)
The | | operator evaluates to true if at least one of the operands is true.
Syntax:
let result = condition1 || condition2;
Example:
fn main() {
let has_password = false;
let has_fingerprint = true;
if has_password || has_fingerprint {
println!("Access granted.");
} else {
println!("Access denied.");
}
}
Output:
Access granted.
3. Logical NOT ( ! )
The ! operator inverts the Boolean value. If the operand is true, it returns false, and vice versa.
Syntax:
let result = !condition;
Example:
fn main() {
let is_authenticated = false;
if !is_authenticated {
println!("Please log in.");
} else {
println!("Welcome back!");
}
}
Output:
Please log in.
Practical Scenarios
Logical operators are essential in writing conditions for control flow. Let’s explore a practical example.
Example: Checking eligibility for a loan:
fn main() {
let age = 30;
let has_income_proof = true;
let has_good_credit = false;
if age >= 18 && (has_income_proof || has_good_credit) {
println!("You are eligible for the loan.");
} else {
println!("You are not eligible for the loan.");
}
}
Output:
You are eligible for the loan.
Important Notes
Short-Circuit Evaluation:
- In &&, if the first operand is false, the second operand is not evaluated.In | |, if the first operand is true, the second operand is not evaluated.
- Example:
fn main() {
let a = false && { println!("This won't print."); true };
let b = true || { println!("This won't print either."); false };
}
Precedence of Operators:
Logical NOT ( ! ) has the highest precedence, followed by Logical AND (&&), and then Logical OR (||).
To ensure clarity, use parentheses for complex expressions.
Example:
let result = !(true || false) && true; // Parentheses clarify precedence
println!("{}", result); // Output: false
Combining Conditions:
Logical operators can be combined to form complex conditions.
Example:
fn main() {
let temperature = 30;
let is_raining = false;
if temperature > 20 && !is_raining {
println!("It's a great day for a picnic!");
} else {
println!("Better stay indoors.");
}
}
Output:
It's a great day for a picnic!