Skip to main content

How to Combine Conditions with AND (&&), OR (||) and NOT (!) in Rust

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

Rust combines bool conditions with three logical operators: a && b is true when both sides are true, a || b when at least one is, and !a turns true into false and false into true. && and || skip their right side when the left side already decides the answer, which lets a check such as !roles.is_empty() protect the code after it.

Syntax​

Syntax
<a> && <b>
<a> || <b>
!<a>
PartWhat it does
<a>, <b>Expressions of type bool, such as age >= 65.
&&AND: true only when both sides are true. When <a> is false, <b> isn't evaluated.
||OR: true when at least one side is true. When <a> is true, <b> isn't evaluated.
!NOT: true becomes false, and false becomes true.

The Rust Reference, Lazy boolean operators: "The operators || and && may be applied to operands of boolean type." And: "|| only evaluates its right-hand operand when the left-hand operand evaluates to false, and && only when it evaluates to true." Its table of Negation operators lists ! as "Logical NOT" on a bool and as "Bitwise NOT" on an integer.

The Example​

The example checks three things about a user: whether they're signed in and not banned, whether a 70-year-old gets a discount meant for children under 12 or people of 65 and over, and the opposite of being signed in. Then it checks whether the first role in an empty list of roles is admin, with a guard that stops it from reading a role that isn't there. A changed version leaves the guard out.

Prerequisites​

  • Rust, with Cargo. This guide uses Rust 1.100.1.

Step 1: Create the Project and Write the Code​

Terminal
cargo new demo
cd demo

cargo new demo creates a project with a src/main.rs. Replace its contents:

src/main.rs, which sets signed_in, banned and age, prints signed_in AND NOT banned, age under 12 OR at least 65, and NOT signed_in, then makes an empty Vec of roles and prints whether it's not empty AND its first role is admin.

src/main.rs
fn main() {
let signed_in = true;
let banned = false;
let age = 70;

println!("{}", signed_in && !banned);
println!("{}", age < 12 || age >= 65);
println!("{}", !signed_in);

let roles: Vec<&str> = Vec::new();
println!("{}", !roles.is_empty() && roles[0] == "admin");
}
  • signed_in && !banned is true only when the user is signed in and not banned.
  • age < 12 || age >= 65 is true for a child or for someone of 65 and over.
  • !signed_in is the opposite of signed_in.
  • let roles: Vec<&str> = Vec::new(); makes an empty list of roles.
  • !roles.is_empty() && roles[0] == "admin" reads the first role only when there is one. roles[0] is the item at index 0, the first one.

Step 2: Run It​

Terminal
cargo run -q
Output
true
true
false
false

-q keeps Cargo quiet, so only the program's output shows. The command is the same in zsh, bash and PowerShell.

Step 3: Leave Out the Guard​

Replace src/main.rs with a version whose last line reads roles[0] without checking that the list has a role:

src/main.rs
fn main() {
let signed_in = true;
let banned = false;
let age = 70;

println!("{}", signed_in && !banned);
println!("{}", age < 12 || age >= 65);
println!("{}", !signed_in);

let roles: Vec<&str> = Vec::new();
println!("{}", roles[0] == "admin");
}
Terminal
cargo run -q
Output
true
true
false

thread 'main' (1514541) panicked at src/main.rs:11:25:
index out of bounds: the len is 0 but the index is 0
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

A zsh terminal where cargo run -q prints true, true, false and false, then, for the changed file, prints true, true and false and panics with index out of bounds, the len is 0 but the index is 0.

What Happened​

  • true: the user is signed in and not banned.
  • true: 70 isn't under 12, but it's 65 or over, so || gave true.
  • false: !signed_in, the opposite of true.
  • false: the list is empty, so !roles.is_empty() was false, and && never evaluated roles[0] == "admin".
  • Without the guard, the program panicked after printing the first three lines: index out of bounds: the len is 0 but the index is 0. The empty Vec has no item at index 0.

Common Mistakes​

MistakeWhat happensDo this instead
and, or or not instead of &&, || and !error: `and` is not a logical operator, with the note "unlike in e.g., Python and PHP, && and || are used for logical operators"Use &&, || and !
!age >= 65 to mean "not 65 or over"It compiles, but ! binds tighter than >=, so it applies to age alone, and on an integer it flips the bits: !age gave -71 for an age of 70Put the comparison in parentheses, !(age >= 65), or write age < 65
A chained comparison, as in 12 < age < 65error: comparison operators cannot be chained, with the help "split the comparison into two"Write 12 < age && age < 65
A number as one side, as in signed_in && itemserror[E0308]: mismatched types: expected bool, found integerCompare the number, as in items > 0
& instead of && in front of an index& always evaluates both sides, so (!roles.is_empty()) & (roles[0] == "admin") panicked on the empty listUse &&

Troubleshooting​

SymptomLikely causeFix
index out of bounds: the len is 0 but the index is 0An index read on an empty VecCheck !roles.is_empty() with && before the index
error: `or` is not a logical operatoror instead of ||Use ||
A mix of && and || gives a result you didn't expect&& is evaluated before ||Add parentheses around the part that goes first

FAQ​

Which comes first, && or ||?​

&&. The Reference's table of expression precedence puts && above ||. In my check, true || false && false gave true, because it's read as true || (false && false), while (true || false) && false gave false. Use parentheses whenever you mix them.

What's the difference between && and &?​

On bool values both mean AND, but & always evaluates both sides. The Reference says the lazy operators "differ from | and & in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression." With &, the guard didn't help: the program panicked on the empty list.

Conclusion​

&&, || and ! combine bool conditions in Rust. && and || stop as soon as the left side decides the answer, so put a guard such as !roles.is_empty() on the left of the check it protects, and add parentheses when you mix the operators or negate a comparison.

Additional Resources​