Rust Reference ยท Operators and Expressions
Rust logical operators
Reference for Rust logical operators &&, || and !: short-circuit evaluation, bool-only operands, bitwise & and | on bool, precedence and let chains.
Rust has three logical operators: && (and), || (or) and ! (not). && and || take two bool operands and short-circuit: the right side is evaluated only when the left side has not already decided the answer. ! flips a single bool.
Rust has no truthiness. Numbers, strings, options and collections are never implicitly converted to a boolean, so conditions must be real bool expressions: write if !items.is_empty() or if count != 0, not if count.
if logged_in && !banned { /* ... */ } let ok = cached || fetch(); // fetch() runs only if cached is false
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
a && b // true if both are true a || b // true if at least one is true !a // logical NOT for bool, bitwise NOT for integers a & b a | b a ^ b // non-short-circuiting operators on bool
| Operator | Evaluates right side | Description |
|---|---|---|
&& |
only if left is true |
Logical AND. |
|| |
only if left is false |
Logical OR. |
! |
n/a | Logical NOT (on bool). |
&, |, ^ |
always | Eager AND, OR, XOR on bool; they evaluate both operands. |
Errors: using a non-bool in a condition gives E0308 (mismatched types, expected bool). Writing && where you meant a pattern with two bindings is a syntax error outside if/while let chains.
Usage notes
- Precedence:
!binds tightest, then&&, then||. Add parentheses when mixing&&and||; the compiler does not warn, but readers will thank you. - Short-circuit for guarding:
i < v.len() && v[i] > 0is the standard bounds-safe pattern; swapping the order panics on the last index. - Side effects hide in the right side. Calls like
a && save()run only whenais true; use anifstatement when the side effect is the point. - Let chains (
if let ... && cond && let ...) are stable in edition 2024 only, since Rust 1.88. They let you test patterns and boolean conditions in a singleiforwhile, and bindings from earlier parts are in scope for later ones. !on integers flips every bit, so!0u8is 255. Usex == 0for a logical "is zero".- No XOR keyword; use
a ^ bora != bfor booleans. - Iterator versions:
allandanyshort-circuit over a sequence, equivalent to chained&&and||. - Match guards (
Some(x) if x > 0 && x < 10) use the same operators. boolmethods:then(|| value)andthen_some(value)turn a condition into anOption.