Reading The Rust Book from cover to cover — Day 2 — Variables
3 min readApr 6, 2024
Talking about Variables and Constants in Rust
Chapter 3: Common Programming Concepts
Variables in Rust are immutable by default.
let x = 5;
// x = 6; won't compile. Compile error: cannot assign twice to immutable variable
Use the keyword mut
to make variables mutable.
Variable shadowing:
- In Rust, you can declare a variable with the same name as a previous variable even within the same scope. This is called Shadowing in Rust.
- Shadowing is different than making the variable mutable with the keyword
mut
. If we try to reassign a value to a shadowed variable without the keywordlet
, we will get a compile-time error. Usinglet
allows the transformations on the value of the variable but the variable is still immutable. - The difference between
mut
and shadowing is that because we’re effectively creating a new variable when we use thelet
keyword again, we can change the type of the value but reuse the same name.
Examples:
For point no 1:
fn main() {
let x = 5;
let x = x + 1;
{
let x = x * 2;
println!("The value of x in the inner scope is: {x}");
}…