Reading The Rust Book from cover to cover — Day 2 — Variables

Jaspreet Kaur
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:

  1. 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.
  2. 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 keyword let, we will get a compile-time error. Using letallows the transformations on the value of the variable but the variable is still immutable.
  3. The difference between mutand 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.

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}");
}…

--

--