Rust Operators: A Comprehensive Guide to Efficient Code Handling

In Rust Program, an operators are symbols or keywords which perform operations on variables and values. Below are some of the common types of operators in Rust Program:

1. Arithmetic Operators

2. Compound Assignment Operators

3. Logical Operators

4. Comparison Operators

5. Bitwise Operators

1. Arithmetic Operators in Rust program :

We can use arithmetic operators to perform addition(+), subtraction(-), multiplication(*), division(/) and Remainder(%).

Please see below a list of various arithmetic operators available in Rust Program. And we have used the variable names a and b in the example.

Screenshot-2024-01-03-192302

Example 1: Addition, Subtraction and Multiplication Operators In Rust :

fn main() {
    let a = 20;
    let b = 2;

    // add two variables using + operator
    let x = a + b;
    println!("{} + {} = {}", a, b, x);

    // subtract two variables using - operator
    let y = a - b;
    println!("{} - {} = {}", a, b, y);

    // multiply two variables using * operator
    let z = a * b;
    println!("{} * {} = {}", a, b, z);
}

Output :

20 + 2 = 22
20 - 2 = 18
20 * 2 = 40

Example 2: Division Operator In Rust :

fn main() {
    let dividend = 21;
    let divisor = 8;

    // arithmetic division using / operator with integers
    let division = dividend / divisor;

    println!("{} / {} = {}", dividend, divisor, division);
}

Output :

21 / 8 = 2

In the upon example, we used the / operator to divide two integers 21 and 8. We fond the output of the operation is 2.

In grade calculation, 21 / 8 gives 2.625. Stall, in Rust, when the use / operator is used with integer values, we found the quotient (integer) as the output.

Screenshot-2024-01-03-193326

Now If you want the correct result, you will use the / operator with floating-point values. For example-

fn main() {
    let dividend = 21.0;
    let divisor = 8.0;

    // arithmetic division using / operator with floating point values
    let division = dividend / divisor;

    println!("{} / {} = {}", dividend, divisor, division);
}

Output :

21 / 8 = 2.625

Above, both dividend and divisor variables are imputed floating point values. In this way, the division operation report a floating point result of 2.625.

Example 3: Remainder Operator In Rust :

In Rust Program, the remainder operator is represented by the % symbol. this calculates the remainder of the division of one number by other number. Please see below an example-

fn main() {
    let dividend = 21;
    let divisor = 8;

    // arithmetic remainder using % operator
    let remainder = dividend % divisor;
  
    println!("{} % {} = {}", dividend, divisor, remainder);
}

Output :

21 % 8 = 5

Above Example, you use the remainder operator % with two integers: 21 and 8. And The above output of the operation is 5.

Now The remainder operator %, as the name suppose, permanently returns the remainder after division.

Screenshot-2024-01-03-194255

2. Compound Assignment Operators In Rust :

We can use an assignment operator to assign a value for a variable. For example-

let x = 5;

Above, = is an assignment operator that assigns the value on the right 5 of the variable xon the left. The assignment operator is on of the most common operator in Rust Program.

Assignment Operators :

In Rust Program, assignment operators are used to assign values to variables where performing some operation on the variable’s current value. The general assignment operators in Rust are similar to which in many other programming languages. Below a list of assignment operators in Rust:

Simple Assignment (=):

its operator assigns the value on the right-hand side to the variable on the left-hand side in below

fn main() {
    let x = 10;
    println!("x: {}", x);
}

Output :

x: 10

Addition Assignment (+=):

In this operator adds the value on the right-hand side to the variable on the left-hand side

fn main() {
    let mut y = 5;
    y += 3; // equivalent to y = y + 3;
    println!("y: {}", y);
}

Output :

y: 8

Subtraction Assignment (-=):

In this operator subtracts value on the right-hand side to the variable on the left-hand side.

fn main() {
    let mut z = 8;
    z -= 2; // equivalent to z = z - 2;
    println!("z: {}", z);
}

Output :

z: 6

Multiplication Assignment (*=):

In this operator multiplies the variable on the left-hand side by the value on the right-hand side.

fn main() {
    let mut a = 4;
    a *= 3; // equivalent to a = a * 3;
    println!("a: {}", a);
}

Output :

a: 12

Division Assignment (/=):

In this operator divides the variable on the left-hand side by the value on the right-hand side.

fn main() {
    let mut b = 12;
    b /= 4; // equivalent to b = b / 4;
    println!("b: {}", b);
}

Output :

b: 3

Remainder Assignment (%=):

In this operator calculates the remainder when dividing the variable on the left-hand side by the value on the right-hand side

fn main() {
    let mut c = 13;
    c %= 5; // equivalent to c = c % 5;
    println!("c: {}", c);
}

Output :

c: 3

Compound Assignment Operators In Rust :

We further use an assignment operator and an arithmetic operator, below known as the a compound assignment operator. For example-

let mut x = 1;

// compound assignment operators
x += 3;

Above, += is a compound assignment operator known as an addition assignment. And this is first adds 3 to the value of x (1) and assigns to the final result (4) to x.

Please see below a list of various compound assignment operators in Rust Programming.

Screenshot-2024-01-03-195152

Example: Compound Assignment Operator In Rust :

fn main() {
    let mut a = 2;
  
    // arithmetic addition and assignment
    a += 3;

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

Output :

a = 5

3.Comparison Operators In Rust :

In Rust Program, comparison operators are used to comparison values and determine their relationship. this operators return a boolean value (true or false) founded on the comparison result. Below are the comparison operators in Rust:

Equality (==) and Inequality (!=):

  • The equality operator (==) restraint if the values on both sides are equal.
  • The inequality operator (!=) restraint if the values on both sides are not equal.
let a = 5;
let b = 7;

println!("a == b: {}", a == b);   // false
println!("a != b: {}", a != b);   // true

Ordering Operators (<, <=, >, >=):

  • Less than (<) restraint if the value on the left is less than the value on the right.
  • Less than or equal to (<=) restraint if the value on the left is less than or equal to the value on the right.
  • Greater than (>) restraint if the value on the left is greater than the value on the right.
  • Greater than or equal to (>=) restraint if the value on the left is greater than or equal to the value on the right
let x = 10;
let y = 15;

println!("x < y: {}", x < y);     // true
println!("x <= y: {}", x <= y);   // true
println!("x > y: {}", x > y);     // false
println!("x >= y: {}", x >= y);   // false

Partial Equality (PartialEq):

Rust Program also supports the PartialEq trait, which accept custom types to implement their own equality comparisons using the == and != operators.

#[derive(Debug, PartialEq)]  // Automatically implements PartialEq trait
struct Point {
    x: i32,
    y: i32,
}

let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 1, y: 2 };

println!("p1 == p2: {}", p1 == p2);   // true

We can use comparison operators to compare two values or variables. For example-

6 > 5

Above, the relational operator > (greater than) checks if 6 is greater than 5.

A relational of operator returns:

a. true in case the relation between two values is correct b. false in case the relation is incorrect

Below a list of comparison operators available in Rust Program.

Screenshot-2024-01-03-203458

Example: Comparison Operators In Rust :

fn main() {
    let a = 7;
    let b = 3;
    
    // use of comparison operators
    let c = a > b;
    let d = a < b;
    let e = a == b;
    
    println!("{} >= {} is {}", a, b, c);
    println!("{} <= {} is {}", a, b, d);
    println!("{} == {} is {}", a, b, e);
}

Output :

7 > 3 is true
7 < 3 is false
7 == 3 is false

4. Logical Operators In Rust :

We also can use logical operators to perform logical judgment or operations. A logical operation returns true or false trust on the conditions. For example-

(5 < 6) && (7 > 4)

In above, && is the logical AND operator which returns true if both conditions are true. In this example, all conditions are true. Below the expression is true.

Below there are mainly 3 logical operators in Rust.

Screenshot-2024-01-03-204049

Example: Logical Operators In Rust :

fn main() {
    let a = true;
    let b = false;
    
    // logical AND operation
    let c = a && b;

    // logical OR operation
    let d = a || b;

    // logical NOT operation
    let e = !a;
    
    println!("{} && {} = {}", a, b, c);
    println!("{} || {} = {}", a, b, d);
    println!("!{} = {}", a, e);
}

Output :

true && false = false
true || false = true
!true = false

Note :

The rational AND and OR operators are also called short-circuiting logical operators because this operators don’t evaluate the complete expression in cases they don’t need to. For example for this expression-

false || true || false

In this || operator evaluates to true because one of the compiler sees a single true expression, it scamper the evaluation and returns true directly.

5.Bitwise Operators in Rust :

In Rust Program, bitwise operators are used to perform operations at the sting level on integers. The bitwise operators are available in Rust Program and its similar to which in many other programming languages. Below are the common bitwise operators in Rust:

Bitwise AND (&) :

  • Syntax: a & b
  • Description: Practice a bitwise AND operation on every pair of corresponding bits in a and b. The result has 1 bit only where both a and b have 1 bit.

Bitwise OR (|):

  • Syntax: a | b
  • Description: Practice a bitwise OR operation on every pair of corresponding bits in a and b. The result has 1 bit where either a or b or both have 1 bit

Bitwise XOR (^):

  • Syntax: a ^ b
  • Description: Practice a bitwise exclusive OR (XOR) operation on every pair of corresponding bits in a and b. The result of a 1 bit where other a or b (but not both) have a 1 bit.

Bitwise NOT (!):

  • Syntax: !a
  • Description: Practice a bitwise NOT operation on every bit of a. It flips every bit, making 1s to 0s and 0s to 1s.

Bitwise Left Shift (<<):

  • Syntax: a << b
  • Description: Change the bits of a to the left by b positions. This is identical to multiplying a by 2^b.

Bitwise Right Shift (>>):

  • Syntax: a >> b
  • Description: Change the bits of a to the right by b positions. This is identical to dividing a by 2^b

Example-Bitwise Operators in Rust:

fn main() {
    let a: u8 = 0b1101; // Binary representation of 13
    let b: u8 = 0b1010; // Binary representation of 10

    let bitwise_and_result = a & b;
    let bitwise_or_result = a | b;
    let bitwise_xor_result = a ^ b;
    let bitwise_not_result = !a;
    let left_shift_result = a << 2;
    let right_shift_result = b >> 1;

    println!("AND: {:08b}", bitwise_and_result);
    println!("OR:  {:08b}", bitwise_or_result);
    println!("XOR: {:08b}", bitwise_xor_result);
    println!("NOT: {:08b}", bitwise_not_result);
    println!("Left Shift:  {:08b}", left_shift_result);
    println!("Right Shift: {:08b}", right_shift_result);
}

Output :

AND: 00000000
OR:  00001111
XOR: 00001101
NOT: 11110011
Left Shift:  11010000
Right Shift: 0101

In above example, {:08b} is used in println! macro to format the output as an 8-bit binary number

Previous
Rust Type Casting: A Comprehensive Guide for Efficient Programming
Next
Conditional Logic in Rust - If-Else-Else-if Statements in RUST