Skip to content

Latest commit

 

History

History
106 lines (74 loc) · 2.14 KB

09. operators.md

File metadata and controls

106 lines (74 loc) · 2.14 KB

Operators

  • Arithmetic Operators : + - * / %
let a = 5;
let b = a + 1; //6
let c = a - 1; //4
let d = a * 2; //10
let e = a / 2; // ⭐️ 2 not 2.5
let f = a % 2; //1

let g = 5.0 / 2.0; //2.5

🔎 Also + is used for array and string concatenation

  • Comparison Operators : == != < > <= >=
let a = 1;
let b = 2;

let c = a == b; //false
let d = a != b; //true
let e = a < b; //true
let f = a > b; //false
let g = a <= a; //true
let h = a >= a; //true

// 🔎
let i = true > false; //true
let j = 'a' > 'A'; //true
  • Logical Operators : ! && ||
let a = true;
let b = false;

let c = !a; //false
let d = a && b; //false
let e = a || b; //true

🔎 On integer types, ! inverts the individual bits in the two’s complement representation of the value.

let a = !-2; //1
let b = !-1; //0
let c = !0; //-1
let d = !1; //-2
  • Bitwise Operators : & | ^ << >>
let a = 1;
let b = 2;

let c = a & b; //0  (01 && 10 -> 00)
let d = a | b; //3  (01 || 10 -> 11)
let e = a ^ b; //3  (01 != 10 -> 11)
let f = a << b; //4  (add 2 positions to the end -> '01'+'00' -> 100)
let g = a >> a; //0  (remove 2 positions from the end -> o̶1̶ -> 0)
  • Assignment and Compound Assignment Operators

The = operator is used to assign a name to a value or a function. Compound Assignment Operators are created by composing one of + - * / % & | ^ << >> operators with = operator.

let mut a = 2;

a += 5; //2 + 5 = 7
a -= 2; //7 - 2 = 5
a *= 5; //5 * 5 = 25
a /= 2; //25 / 2 = 12 not 12.5
a %= 5; //12 % 5 = 2

a &= 2; //10 && 10 -> 10 -> 2
a |= 5; //010 || 101 -> 111 -> 7
a ^= 2; //111 != 010 -> 101 -> 5
a <<= 1; //'101'+'0' -> 1010 -> 10
a >>= 2; //101̶0̶ -> 10 -> 2
  • Type Casting Operator : as
let a = 15;
let b = (a as f64) / 2.0; //7.5
  • Borrowing and Dereference Operators : & &mut *

The & or &mut operators are used for borrowing and ***** operator for Dereferencing.

🔎 Usage of these operators is an advanced topic, for more information use Rust Reference Documentation.