Introduction
Variables in Rust are immutable by default. This is one major difference when compared to other Programming languages, where it is okay to change the values of variables, unless it is explicitly declared as a constant. In Rust we're doing the opposite, and in this article we'll see how?
How to declare variables?
We can declare variables using the let keyword in Rust.
fn main() {
let x = 2;
let y = "four";
}
But if we try to reassign the value of x, we'll get an error.
fn main() {
let x = 2;
x = 6;
}
The above code will throw an error because variables in Rust are immutable by default.
2 | let x = 2;
| -
| |
| first assignment to `x`
| help: consider making this binding mutable: `mut x`
3 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
The compiler is another beauty of Rust! The message is so clear, I don't have to say anything more.
Now coming to the more important question, how to declare mutable variables in Rust?
fn main() {
let mut x = 2;
x = 6;
}
We have to use the keyword mut and that's it. Now there will be no annoying errors!
Shadowing
Apart from using mut, there seems to be another way of changing the value of x. And this is something that we call shadowing
fn main() {
let x = 2;
println!("{x}"); // 2
let x = 6;
println!("{x}"); // 6
}
Here the value of the 1st x gets overwritten by that of the 2nd x.
But the 2nd x is still immutable. To change it's value we have to create a 3rd x using the let keyword, then assign some value. This is the difference between mut & shadowing
Constants
When we have immutable variables, why do we need constants, is what you might be wondering right now! But trust me here, we need 'em.
const x = 3;
let x = 6;
The above code will throw an error.
Because value of constants can never be changed!
Also it's a common convention to use all uppercase characters while declaring constants. Like below:
const LENGTH = 8;
And that's all you need to know about variables in Rust for a long long time!
Conclusion
Although we have learnt about variables, we haven't yet learnt about Data types, which covers the other aspect of variables of a Strongly typed language, Rust in our case. And we'll learn about this in the next article. Cheers!