Rust Operators

Types of Operators in Rust

Rust categorizes its operators into the following types:

  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Logical Operators
  4. Bitwise Operators
  5. Assignment Operators
  6. Compound Assignment Operators
  7. Miscellaneous Operators

1. Arithmetic Operators

Arithmetic operators are used for mathematical calculations.

OperatorDescriptionExampleOutput
+Addition5 + 38
Subtraction5 – 32
*Multiplication5 * 315
/Division (Integer/F64)5 / 22 (int)
%Modulus (Remainder)5 % 21

Example:

fn main() {
let a = 10;
let b = 3;
println!("Addition: {}", a + b);
println!("Subtraction: {}", a - b);
println!("Multiplication: {}", a * b);
println!("Division: {}", a / b);
println!("Remainder: {}", a % b);
}

2. Comparison (Relational) Operators

Comparison operators are used to compare two values and return a Boolean result (true or false).

OperatorDescriptionExampleOutput
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to3 <= 5true

Example:

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

3. Logical Operators

Logical operators are used to combine or negate Boolean expressions.

OperatorDescriptionExampleOutput
&&Logical ANDtrue && falsefalse
``Logical OR
!Logical NOT!truefalse

Example:

fn main() {
let x = true;
let y = false;
println!("x && y: {}", x && y);
println!("x || y: {}", x || y);
println!("!x: {}", !x);
}

4. Bitwise Operators

Bitwise operators work on binary representations of integers.

OperatorDescriptionExampleOutput
&Bitwise AND5 & 31
``Bitwise OR`5
^Bitwise XOR5 ^ 36
<<Left Shift5 << 110
>>Right Shift5 >> 12

Example:

fn main() {
let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
println!("Bitwise AND: {}", a & b);
println!("Bitwise OR: {}", a | b);
println!("Bitwise XOR: {}", a ^ b);
println!("Left Shift: {}", a << 1);
println!("Right Shift: {}", a >> 1);
}

5. Assignment Operators

Assignment operators assign values to variables.

OperatorDescriptionExampleOutput
=Assignlet x = 5x = 5

Example:

fn main() {
let x = 10; // Assigning 10 to x
println!("Value of x: {}", x);
}

6. Compound Assignment Operators

These operators combine basic operations with assignment.

OperatorDescriptionExampleEquivalent To
+=Add and assignx += 5x = x + 5
-=Subtract and assignx -= 5x = x – 5
*=Multiply and assignx *= 5x = x * 5
/=Divide and assignx /= 5x = x / 5
%=Modulus and assignx %= 5x = x % 5

Example:

fn main() {
let mut x = 10;
x += 5;
println!("After addition: {}", x);
x *= 2;
println!("After multiplication: {}", x);
}

7. Miscellaneous Operators

OperatorDescriptionExampleOutput
.Access a field or methodmy_struct.xAccess x
->Access a pointerptr->fieldAccess field

Leave a Comment

BoxofLearn