Rust Programming : Data Types (Section-2)

Assalamu'alaikum wr. wb

Compound Types
Hasil gambar untuk data type rustCompound types can group multiple values into one type. Rust has two primitive compound types : tuples and arrays.

  • The Tuple Type
A tupple is a general way of grouping together some number of other values with a variety of types into one compound type. Tuples have a fixed lenght, once declared they can't grow or shrink in size. We create a tuple by writing a comma-separated list of values inside parentheses. Each position in the tuple has a type, and the types of the different values in the tuple don't have to be same. We've added optional type annotations in this example :

fn main(){
let tup: (i32, f64, u8) = (200, 6.7, 3);
}

The variable tup binds to the entire tuple, because a tuple is considered a single compound element. To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value like this :

fn main(){
let tup = (200, 6.7, 3);
let x, y, z = tup;
print!("The values of y is {}", y);
}

This program first creates a tuple and binds it to the variable tup. It the uses a pattern with let to take tup and turn it into three separate variables x, y & z. This is called destructuring, because it breaks the single tuple into three parts. Finally, the program print the value y, which is 6.7.

In addition to destructuring through pattern matching we can access a tuple element directly by using a period (.) followed by the index of the value we want to access. For example :

fn main(){
let x:f64, i32, u8 = (100, 6.3, 7);
let one_hundred = x.0;
let six_point_three = x.1;
let seven = x.2;
}

This program creates a tuple x, and then makes new variables for each element by using their index. As with most programming languages, the first index in a tuple is 0.

  • The Array Type
Another way to have a collection of multiple values is with an array. Unlike a tuple, every element of an array must have the same type. Arrays is Rust are different from arrays in some other languages because arrays in Rust have fixed lenght like tuples. In Rust, the value going into an array are written as a comma-separated list inside square brackets:

fn main(){
let _array = [5, 3, 2, 7, 9];
}

Arrays are useful when we want our data allocated on the stack rather than the heap or when we want to ensure always have a fixed values number of elements. An array isn't as flexible as the vector type, though. A vector is similiar collection type provided by the standard library that is followed to grow or shrink in size. If we're unsure whether to use an array or a vector, we should probrably use a vector. 

An example of when we might to use an array rather than a vector is in a program  that needs to know the names of the month of the year. It's very unlikely that such a program will need to add or remove months. So, we can use an array because we know it will always contain 12 items :

fn main(){
let months = ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"];

Arrays have an interesting type; it looks like this :
[type, number]
For example :

fn main(){
let a:[i32, 5] = [1,2,3,4,5];
}

Firts, there's square bracket's they look like the syntax for creating an array. Inside, there's two pieces of information, separated by semicolon. The first is the type of each element of the array. Since all elements have the same type, we only need to list it once. After the semicolon, there's a number that  indicates the lenght of the array. Since an array has a fixed size, this number is always the same. Even if the array's elements are modified it can't grow or shrink.

Now, how to access the array's value / elements ?
An array is a single chunk of memory allocated on the stack. We can access elements of an array using indexing, like this :

fn main(){
let a = [1,2,3,4,5];

let first = a[0];
let second = a[1];
}

In this example the variable named first will get the value 1 because that is the value at index [0] in the array. The variable named second will get value 2 from index [1] in the array.

What happen if we access out of the index ? 
Let's write code below and run with cargo run command :

fn main(){
let my_array = [1,2,3,4,5];

let index = 8;
let element = my_array[index];

print!("The value of element is {}", element);
}

We'll get information like this :

"thread panicked ..."

The compilation didn't produce any errors, but the program resulted in runtime-error and didn't exit successfully. Whe we attemp to access an element using indexing, Rust will check that the index we've specified is less than the array  lenght. If the index is greater than the lenght, Rust will panic.

This is first example of Rust's safety principles in action. In many low-level languages, this kind of check is not done, and when we provide an incorrect index, invalid memory can be accessed. Rust protects we againts this kind of error by immediately exiting instead of allowing the memory access and continuing.

It looks enaugh for this night guys, selamat malam dan selamat belajar ....

Wassalamu'alaikum wr. wb  


Ahmad Istakim

Alumni dari jurusan Manajemen Informatika di Universitas Sains Al-Qur'an (UNSIQ ) Wonosobo. Tertarik dalam bidang pendidikan, teknologi komputasi dan disiplin ilmu keislaman ( Tafsir, Hadits, Arudl, Nahwu-Sharaf, Fiqh maupun Aqidah ) - https://s.id/blog-islamQ. Pernah juga mengenyam pendidikan di beberapa pesantren yang ada di Kab. Wonosobo dan Kab. Purworejo

Posting Komentar

Lebih baru Lebih lama