Variables and Immutability

Learn how variables work in Rust and why they are immutable by default.

Beginner⏱️ 20 min📚 Prerequisites: 1

Variables and Immutability

In Rust, variables are immutable (unchangeable) by default. This means that a variable's value cannot be modified unless we explicitly mark it with the mut keyword.

Basic Syntax

RUST
let x = 5;        // immutable variable
let mut y = 10;   // mutable (changeable) variable

Why Immutable by Default?

This design decision provides several advantages:

  • Safety: Reduces the possibility of accidental modifications
  • Concurrent Programming: Easier to write safe code
  • Readability: Clear which variables can be modified

Shadowing

Rust allows shadowing, when we create a new variable with the same name:

RUST
let x = 5;
let x = x + 1;  // new variable, not modification

This is different from mut, because it creates a completely new variable.

Code Examples

Immutable Variable

Example of an immutable variable

RUST
fn main() {
    let x = 5;
    println!("x value: {}", x);
}

Explanation:

The `x` variable is immutable, so it cannot be modified. If we try to modify it, the compiler will signal an error.

Blockchain: Immutable Address

Using immutability for blockchain addresses

RUST
fn main() {
    let wallet_address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb";
    println!("Wallet address: {}", wallet_address);
}

Explanation:

In blockchain, addresses and other identifiers should be immutable to prevent accidental changes that could lead to security issues.

Mutable Variable

Example of a mutable variable

RUST
fn main() {
    let mut x = 5;
    println!("Original value: {}", x);
    x = 6;
    println!("New value: {}", x);
}

Explanation:

A variable marked with the `mut` keyword is mutable. This allows us to assign a new value to it.

Blockchain: Mutable Balance

Using mutability for changing balances

RUST
fn main() {
    let mut account_balance: u64 = 1000;
    println!("Initial balance: {} tokens", account_balance);
    account_balance += 500;
    println!("After receiving: {} tokens", account_balance);
    account_balance -= 200;
    println!("After sending: {} tokens", account_balance);
}

Explanation:

In blockchain, account balances must be mutable because they change with each transaction. The `mut` keyword allows us to update the balance.

Shadowing Example

How shadowing works

RUST
fn main() {
    let x = 5;
    let x = x + 1;
    let x = x * 2;
    println!("x value: {}", x);
}

Explanation:

Shadowing allows us to create a new variable with the same name. Each `let` creates a new variable that shadows the previous one.

Exercises

Variable Modification

Create a mutable variable that you modify!

Easy

Starter Code:

RUST
fn main() {
}

Blockchain: Track Balance

Create a mutable balance variable and simulate transactions!

Easy

Starter Code:

RUST
fn main() {
}