Logical Operators
Logical operators operate on bool values and produce bool results.
Logical NOT
The logical NOT operator ! negates its operand.
fn main() -> i32 {
let a = !false; // true
let b = !true; // false
let c = !!true; // true (double negation)
if a { 1 } else { 0 }
}
Logical AND
The logical AND operator && returns true if both operands are true.
The && operator uses short-circuit evaluation: if the left operand is false, the right operand is not evaluated.
fn main() -> i32 {
if true && true { 1 } else { 0 } // 1
if true && false { 1 } else { 0 } // 0
}
Logical OR
The logical OR operator || returns true if either operand is true.
The || operator uses short-circuit evaluation: if the left operand is true, the right operand is not evaluated.
fn main() -> i32 {
if false || true { 1 } else { 0 } // 1
if false || false { 1 } else { 0 } // 0
}
Precedence
Operator precedence (highest to lowest):
!(logical NOT)&&(logical AND)||(logical OR)
fn main() -> i32 {
// true || false && false => true || (false && false) => true
if true || false && false { 1 } else { 0 }
}
Type Checking
All operands of logical operators MUST have type bool.