DEV Community

Adi Purwanto
Adi Purwanto

Posted on

Stage 4 - Operators | Belajar Rust #5

Operators merupakan sebuah simbol yang mengambil satu atau lebih values dan kemudian mengeluarkan value lainnya, operator memberitahukan compiler untuk melakukan beberapa operasi. Rust memiliki banyak operators yang berbeda untuk melakukan berbagai macam operasi. Operators memiliki dua kategori berdasarkan number of operands, yaitu unary dan binary operators.

  • Unary operators → operators yang bekerja pada single operand
    • Borrow expression → &, &mut;
    • Dereference expression → *;
    • Negation expression → !;
    • Logical negation expression.
  • Binary operators → operators yang menangani dua operands
    • Arithmetic expression → +, -, *, /, %;
    • Logical expression → &&, ||;
    • Comparison expression → >, <, >=, <=, !=, ==;
    • Assignment expression → =;
    • Compound assignment expression → -=, +=, /=, *=, %=;
    • Bitwise expression → &, |, ^;
    • Typecast expression → as.

Kita bahas satu-persatu dari list operators diatas berikut.

1. Arithmetic operators

Ketika kita ingin menggunakan operasi aritmatika anak sd, kita bisa menggunakan arithmetic operators.

operand 1 [...] operand 2 // [+, -, *, %, atau /]
Enter fullscreen mode Exit fullscreen mode
Operator Operation Explanation
+ Addition Menambah dua operand
- Subtraction Mengurangi dua operand
/ Division Membagi dua operand
* Multiplication Mengkalikan dua operand
% Modulus Hasil sisa bagi dua operand

→ Contoh

fn main() {
  let x = 8;
  let y = 4;

  println!("x: {} dan 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);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 8 dan y: 4
x + y = 12
x - y = 4
x / y = 2
x * y = 32
x % y = 0
Enter fullscreen mode Exit fullscreen mode

2. Logical operators

Operators ini memiliki tugas untuk mengoperasikan true/ false values.

operand 1 [...] operand 2 // [&&, ||] -> binary operators
operand 2 [...] operand 1 // [!] -> unary operators
Enter fullscreen mode Exit fullscreen mode
Operator Operation Explanation
&& AND true jika kedua operand true
! NOT Negasi value dari single operand

→ Contoh

fn main() {
  let x = false;
  let y = true;

  println!("x: {} dan y: {}", x, y);
  println!("x && y = {}", x && y);
  println!("x || y = {}", x || y);
  println!("!y = {}", !y);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: false dan y: true
x && y = false
x || y = true
!y = false
Enter fullscreen mode Exit fullscreen mode

3. Comparison operators

Operators ini digunakan untuk melakukan komparasi values dari dua operands.

operand 1 [...] operand 2 // [<, >, <=, >=, ==, atau !=]
Enter fullscreen mode Exit fullscreen mode
Operator Operation Explanation
> Greater than true jika salah satu operand lebih besar dari operand satunya
< Lesser than true jika salah satu operand lebih kecil dari operand satunya
>= Greater than equal to true jika salah satu operand lebih besar atau sama dengan dari operand satunya
<= Lesser than equal to true jika salah satu operand lebih kecil atau sama dengan dari operand satunya
== Equals to true jika kedua operand sama
!= Not equal to true jika kedua operand tidak sama

→ Contoh

fn main() {
  let x = 8;
  let y = 7;

  println!("x: {} dan 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);
  println!("x != y = {}", x != y);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 8 dan y: 7
x > y = true
x < y = false
x >= y = true
x <= y = false
x == y = false
x != y = true
Enter fullscreen mode Exit fullscreen mode

4. Bitwise operators

Operators ini menghandle binary representation dari operands.

operand 1 [...] operand 2 // [&, |, ^] -> binary operators
[...] operand 1 // [!, <<, >>] -> unary operators
Enter fullscreen mode Exit fullscreen mode
Operator Operation Explanation
& AND Bitwise AND kedua operands
OR
^ XOR Bitwise XOR kedua operands
! NOT Inverse bits dari operand
<< Left shift Memindahkan semua bit dalam operand pertama ke kiri dengan jumlah tempat yang ditentukan dalam operand kedua. Bit baru diisi dengan nol. Menggeser nilai ke kiri satu posisi sama dengan mengalikannya dengan 2, menggeser dua posisi sama dengan mengalikannya dengan 4, dan seterusnya.
>> Right shift Nilai operand kiri dipindahkan ke kanan dengan jumlah bit yang ditentukan oleh operand kanan.

→ Contoh

fn main() {
  let x = 8;
  let y = 7;

  println!("x: {} dan y: {}", x, y);
  println!("x & y = {}", x & y);
  println!("x | y = {}", x | y);
  println!("x ^ y = {}", x ^ y);
  println!("!y = {}", !y);
  println!("x << 4 = {}", x << 4);
  println!("x >> 2 = {}", x >> 2);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 8 dan y: 7
x & y = 0
x | y = 15
x ^ y = 15
!y = -8
x << 4 = 128
x >> 2 = 2
Enter fullscreen mode Exit fullscreen mode

5. Assignment dan compound assignment operators

a. Assignment operator

Operator ini digunakan untuk menyimpan value ke dalam variable.

operand 1 = operand 2
Enter fullscreen mode Exit fullscreen mode

→ Contoh

fn main() {
  let x = 8;
  let y = 7;
  let z = x + y;

  println!("x: {}, y: {}, dan z:{}", x, y, z);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 8, y: 7, dan z:15
Enter fullscreen mode Exit fullscreen mode

b. Compound assignment operator

Operator ini memiliki tugas untuk melakukan operasi dan kemudian menetapkan nilai tersebut ke operand.

operand 1 [...] operand 2 // [+=, -=, /=, *=, &=, !=, ^=, <<=, atau >>=]
// contoh a *= x -> a = a * x
Enter fullscreen mode Exit fullscreen mode

→ Contoh

fn main() {
  let mut x = 8;

  println!("x: {}", x);
  x += 1;
  println!("x: {}", x);
  x -= 2;
  println!("x: {}", x);
  x *= 2;
  println!("x: {}", x);
  x /= 7;
  println!("x: {}", x);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 8
x: 9
x: 7
x: 14
x: 2
Enter fullscreen mode Exit fullscreen mode

6. Type casting operator

Operator ini diperlukan ketika kita ingin mengkonversi data type dari variable ke data type yang lain.

operand as datatype
Enter fullscreen mode Exit fullscreen mode

→ Contoh

fn main() {
  let x = 15;
  let y = (x as f64) / 4.0;

  println!("x: {} dan y: {}", x, y);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

x: 15 dan y: 3.75
Enter fullscreen mode Exit fullscreen mode

📝 Data types apa saja yang bisa kita casting?

  • Integer ke floating-point dan sebaliknya
  • Integer ke string

📝 Data types apa saja yang tidak bisa kita casting?

  • String (&str) atau character tidak bisa ke integer atau float
  • Character tidak bisa ke String dan sebaliknya

7. Borrowing dan dereferencing operators

a. Borrowing operator

Borrowing atau yang artinya reference pada binding data asli atau share the data.

Jika kalian pernah menggunakan C, References sama seperti pointers dalam C

borrowing

let operand 1 = [&, atau &mut] operand 2
Enter fullscreen mode Exit fullscreen mode
Operator Operation Explanation
& shared borrow operand bisa membaca data dari operand lainnya
&mut mutable borrow operand bisa membaca dan mengubah data dari perand lainnya

b. Dereferencing operator

Setelah Anda memiliki mutable reference ke suatu variabel, dereferencing adalah istilah yang digunakan untuk merujuk pada perubahan nilai referenced variabel menggunakan address yang disimpan dalam referring variabel.

let operand 1 = &mut operand 2;
*operand 1 = operand 2 // mengubah value dari variable yang di borrow
Enter fullscreen mode Exit fullscreen mode

→ Contoh

fn main() {
    let x = 14;
    let mut y = 12;
    //immutable reference to a variable
    let a = &x;
    println!("Value of a:{}", a); 
    println!("Value of x:{}", x); // x value remains the same since it is immutably borrowed
    //mutable reference to a variable
    let b = &mut y;
    println!("Value of b:{}", b);

    *b = 11; // derefencing 
    println!("Value of b:{}", b); // updated value of b
    println!("Value of y:{}", y); // y value can be changed as it is mutuably borrowed
}
Enter fullscreen mode Exit fullscreen mode

→ Output

Value of a:14
Value of x:14
Value of b:12
Value of b:11
Value of y:11
Enter fullscreen mode Exit fullscreen mode

8. Precedence dan associativity

a. Precedence

Ini menentukan operasi mana yang dilakukan pertama kali dalam ekspresi dengan lebih dari satu operator. Operator berikut merupakan urutan prioritas mereka dari tertinggi ke terendah.

  • Unary
    • Logical/Bitwise NOT - !
    • Derereference - *
    • Borrow - &&mut
  • Binary
    • Typecast - as
    • Multiplication- *,Division - /, Remainder - %
    • Addition -+, Subtraction - -
    • Left Shift - <<, Right Shift - >>
    • Bitwise AND - &
    • Bitwise XOR - ^
    • Bitwise OR - |
    • Comparison - == != < > <= >=
    • Logical AND - &&
    • Logical OR - ||
    • Range - start .. stop
    • Assignment/Compound Assignment - = += = = /= %= &= |= ^= <<= >>=

Note: Operator yang ditulis pada baris yang sama memiliki urutan prioritas yang sama.

b. Associativity

Jika dua atau lebih operator dengan precedence yang sama muncul dalam sebuah pernyataan, maka operator mana yang akan dievaluasi terlebih dahulu ditentukan oleh associativity.

Left to Right Associativity

Left associativity terjadi ketika expression dievaluasi dari kiri ke kanan. Expression seperti a ~ b ~ c, dalam hal ini, akan ditafsirkan sebagai (a ~ b) ~ c di mana ~ dapat berupa operator apa pun. Operator di bawah ini dapat dirantai sebagai left associative.

  • as
  • */%
  • +-
  • << >>
  • &
  • ^
  • |
  • &&
  • ||

→ Contoh

fn main() {
    println!("Jawaban UAS : {}",( 10 + 5 ) * 8 / 7 & 8);
}
Enter fullscreen mode Exit fullscreen mode

→ Output

Jawaban UAS : 0
Enter fullscreen mode Exit fullscreen mode

Jika ada kesalahan dalam menyampaikan konsep dan penulisan mohon bantuannya di kolom discussion 🤗. Terima kasih.

#samasamabelajar


LIST COURSE:

If you don't know me, then, you would not know who I am

Stage 1

Stage 2 - Variables

Stage 3 - Data Types


Twitter

Buy me a coffe

Top comments (0)