Rust Logical Operators

Logical Operators in the Rust Language: AND, OR, NOT

In the Rust programming language, logical operators are symbols that are used to perform logic operations.

There are three logical operators in Rust: AND, OR, and NOT.

Logical operators are designed to work with Boolean data types. They are a type of operator that receives a Boolean input and produces a Boolean output. This means that they operate on and produce true/false values.

OperatorOperationSyntaxFunction
&&ANDa && bTrue if both operands are true
||ORa || bTrue if at least one operand is true
!NOT!Switches true to false or false to true

AND Operator

The AND operator is ‘&&‘. It evaluates two Boolean inputs and outputs true only if both operands are true.

AND Operator Truth Table

The following truth table shows the possible results of the AND operator:

Operand AOperand BA && B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

AND Operator Example

let a = true;
let b = false;

println!("{}", a && b);

Standard Output:

false

OR Operator

The OR operator is ‘||‘. It evaluates two Boolean inputs and outputs true if at least one operand is true.

OR Operator Truth Table

The following truth table shows the possible results of the OR operator:

Operand AOperand BA || B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

OR Operator Example

let a = true;
let b = false;

println!("{}", a || b);

Standard Output:

true

NOT Operator

The NOT operator is ‘!‘. It is a unary operator, meaning that it acts on a single operand; it has one input and one output. NOT evaluates a single Boolean input and negates its value. A value of true will become false, and a value of false will become true.

NOT Operator Truth Table

The following truth table shows the possible results of the NOT operator:

Operand A!A
TrueTrue
FalseFalse

NOT Operator Example

let a = true;

println!("{}", !a);

Standard Output:

false

Lazy Boolean Expressions

In Rust, the first operand of an AND or an OR expression is evaluated first.

If the first AND operand is false, there is no need for the other to be evaluated because the expression will always be false.

Similarly, if the first operand in an OR expression is true, the whole expression will always be true.

Rust takes advantage of this by using short-circuit evaluation to reduce computational demand. The AND and OR expressions are considered ‘lazy’ because the second operand is only evaluated after the first.