Rust Programming : Variables and Mutability

Assalamu'alaikum wr. wb


  • Mutability

Hasil gambar untuk data type rustBy default variables are immutable. This is one if many nudges Rust gives us to write our code in a way that takes advantage of the safety and easy concurrency that Rust offers. However, we still have the option to make our variables mutable. When a variable is immutable, once a value is bound to a name. We can' change that value.
Let' see the example :


fn main(){
let x = 5;
println!("The value x is {}", x);
x = 6;
println!("The value x is {}", x);
}

It's important that we get compile-time-errors when we attemp to change a value that we previously designated as immutable because this very situation can lead to bugs. If one part of our code operates on the assumption that a value will never change and another part of our code canges that value, it's possible that the first part of the code won't do what it was designed to do. The cause of this kind of bug can be difficult to track down after the fact, especially when the second of piece of the code changes the value only one times.

 In Rust, the compiler guarantees that when us state that a value won't change, it really won't change. That means that when you're reading and writing code, we don't have to keep track of how and where a value might change. Our code is thus easier to reason through.

But mutability can be useful. Variables are immutable only by default, as we did knew. We can make a variable mutable by adding mut in front of variable name. In addition to allowing this value to change, mut conveys intent to future readers of the code by indicating that other parts of the code will be changing this variable value.

We're allowed to change x value that binds from 5 to 6 when mut is used. In some cases, you'll want to make a variable mutable because it makes the code more convenient to write than if it hand only immutable variables.

There are multiple trade-offs to consider in addition to the prevention of bugs. For example, in cases  when you're using large data and structures, mutating an instance in place maybe faster than copying and returning newly allocated instances. With smaller data structures, creating new instances and writing in a more functional programming style may be easier to think through, so lower performance might be a worthwhile penalty for gaining that clarity.


  • Differences Between Mutability and Contants
Being unable to change the value of data variable might have be reminded us of another programming concept that most other languages have : contants. Like immutable variable, contants are values that are bound to a name and are not allowed to change, but there are a few differences between contants and variables.

First, we're not allowed to use mut with constants. Constants are just immutable by defaut, they're always immutable. We declare contants with const keyword instead of the let keyword, and the type of the value must be annotated.

Second, constants can be declared in any scope, including the global scope, which makes the useful for values that many parts of the code need to know about.

And the last difference is that constants may be set only to a constants expression, not the result of a function call or any other value that could only be computated at runtime. Here's an example of a constant declaration where the constant's name is MAX_POINTS and its value is set to 100,000.
(Warning : Rust's naming convention for constants is to use all uppercase with underscores between words and underscores can be inserted in numeric literals to improve redibility).     

const MAX_POINTS : u32 = 100_000;

Constants are valid for the entire time a program runs, within the scope they were declared in, making them a useful choice for values in our application domain that multiple parts of the program might need to know about it, such as the maximum number of points any player of a game is allowed to earn or the speed of light.

Naming hardcoded values used throughout our program as constants is useful in conveying the meaning of that value to future mainteners of the code. It also helps to have only one place in our code we would need to change if the hardcoded value needed value to needed to be updated in the future.


  • Shadowing 
In Rust, we're allowed to declare a new variable with the same name as a previous variable, and the new variable shadows the previous variable. Rustacean say that the first variable is shadowed by the second. Which mean that the second variables value is what appears when the variable is used. We can shadow a variable by using the same variable's name and repeating the use of the let keyword as follows :

fn main(){
let x = 5;
let x = x + 5;
let x = x * 2;

println!("The value of x is {}", x);
}

This program first binds to value of 5. Than it shadows x by repeating let x, taking the original value and adding 5 so the value of x is 10. The third let statement also shadows x, multiplying the previous value by 2 to give x final value of 20.

Shadowing is different than marking a variable as mut, because we'll get a compile-time-error if we accidentally try to reassign to this variable without using the let keyword. By using let, we can perform a few tranformations have been completed.

The other difference between mut and shadowing is that because we're effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.

Now, we've explored how variables works. Let's look at more data types they can have.....

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