RRust By Example
beginnerBasics

Variables and Mutability

Understand let bindings, mut keyword, and shadowing.

Variables and Mutability

Understand let bindings, mut keyword, and shadowing.

Difficulty

Beginner

Code

rust
fn main() {
    let x = 5;
    // x = 6; // error: cannot assign twice to immutable variable
    println!("x = {}", x);

    let mut y = 10;
    y = 20;
    println!("y = {}", y);

    // shadowing
    let z = 5;
    let z = z + 1;
    let z = z * 2;
    println!("z = {}", z); // 12

    // shadowing can change type
    let spaces = "   ";
    let spaces = spaces.len();
    println!("spaces: {}", spaces);
}

Explanation

Variables are immutable by default. mut enables mutation. Shadowing creates new bindings.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples