Bird
Raised Fist0
Rustprogramming~10 mins

Scope of variables in Rust - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Scope of variables
Start of program
↓
Declare variable in main scope
↓
Enter inner block
↓
Declare variable in inner block
↓
Use variables
↓
Exit inner block
↓
Try to use inner block variable (error)
↓
End of program
This flow shows how variables declared inside blocks are only usable within those blocks, while variables declared outside are accessible inside.
Execution Sample
Rust
fn main() {
    let x = 5;
    {
        let y = 10;
        println!("x = {}, y = {}", x, y);
    }
    println!("x = {}", x);
    // println!("y = {}", y); // Error: y not in scope
}
This Rust code shows variable x declared in main scope and y declared inside an inner block; y is not accessible outside.
Execution Table
StepActionVariables in ScopeOutputNotes
1Declare x = 5 in main scopex=5x is accessible everywhere in main after this
2Enter inner blockx=5Inner block starts, x still accessible
3Declare y = 10 in inner blockx=5, y=10y is only accessible inside this block
4Print x and yx=5, y=10x = 5, y = 10Both variables accessible here
5Exit inner blockx=5y goes out of scope, no longer accessible
6Print xx=5x = 5x still accessible
7Attempt to print y (commented out)x=5Error if uncommented: y not in scope
💡 Program ends after main function finishes; inner block variables are dropped after block ends.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5Final
xundefined5555
yundefinedundefined10undefinedundefined
Key Moments - 2 Insights
Why can't we use variable y outside the inner block?
Because y is declared inside the inner block (see step 3 and 5 in execution_table), it only exists within that block's scope and is dropped after the block ends.
Is variable x accessible inside the inner block?
Yes, x is declared in the main scope before the inner block (step 1), so it is accessible inside the inner block (step 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what variables are in scope?
AOnly x
Bx and y
COnly y
DNeither x nor y
💡 Hint
Check the 'Variables in Scope' column at step 4 in execution_table.
At which step does variable y go out of scope?
AStep 5
BStep 3
CStep 6
DStep 7
💡 Hint
Look at the 'Variables in Scope' column before and after step 5 in execution_table.
If we declare y outside the inner block, how would the variable_tracker change?
Ay would only appear after step 3
By would be undefined throughout
Cy would have a value starting from step 1 and remain until final
Dy would disappear after step 5
💡 Hint
Variable declared outside block stays in scope throughout; see variable_tracker for x.
Concept Snapshot
Scope of variables in Rust:
- Variables declared inside a block {} are only accessible inside that block.
- Variables declared outside are accessible inside inner blocks.
- After the block ends, inner variables go out of scope and cannot be used.
- Trying to use out-of-scope variables causes compile errors.
Full Transcript
This visual execution shows how Rust handles variable scope. Variable x is declared in the main function and is accessible everywhere inside main. Variable y is declared inside an inner block and is only accessible within that block. When the block ends, y goes out of scope and cannot be used anymore. The execution table traces each step, showing which variables are in scope and what output is produced. Key moments clarify why y is not accessible outside the block and confirm that x is accessible inside. The quiz tests understanding of variable scope changes during execution.

Practice

(1/5)
1. What does the scope of a variable in Rust determine?
easy
A. Where the variable can be accessed or used
B. The type of the variable
C. The value stored in the variable
D. The memory size of the variable

Solution

  1. Step 1: Understand the meaning of scope

    Scope means the part of the code where a variable is valid and can be used.
  2. Step 2: Identify what scope controls

    Scope controls access to the variable, not its type, value, or memory size.
  3. Final Answer:

    Where the variable can be accessed or used -> Option A
  4. Quick Check:

    Scope = access area [OK]
Hint: Scope means where you can use the variable [OK]
Common Mistakes:
  • Confusing scope with variable type
  • Thinking scope controls variable value
  • Mixing scope with memory size
2. Which of the following is the correct way to declare a variable inside a block in Rust?
easy
A. var x = 5;
B. let x = 5;
C. int x = 5;
D. declare x = 5;

Solution

  1. Step 1: Recall Rust variable declaration syntax

    Rust uses let keyword to declare variables.
  2. Step 2: Check each option

    Only let x = 5; is valid Rust syntax; others are from other languages or invalid.
  3. Final Answer:

    let x = 5; -> Option B
  4. Quick Check:

    Rust variables start with let [OK]
Hint: Rust variables start with let keyword [OK]
Common Mistakes:
  • Using var instead of let
  • Using type declarations like int
  • Using declare keyword
3. What will be the output of this Rust code?
fn main() {
    let x = 10;
    {
        let x = 20;
        println!("{}", x);
    }
    println!("{}", x);
}
medium
A. 10\n10
B. 20\n20
C. 10\n20
D. 20\n10

Solution

  1. Step 1: Identify variable shadowing inside inner block

    Inside the inner block, x is redefined as 20, shadowing outer x.
  2. Step 2: Trace the print statements

    First print shows inner x = 20; second print shows outer x = 10.
  3. Final Answer:

    20 10 -> Option D
  4. Quick Check:

    Inner shadow = 20, outer original = 10 [OK]
Hint: Inner block shadows outer variable [OK]
Common Mistakes:
  • Ignoring shadowing and printing outer value twice
  • Assuming inner variable changes outer variable
  • Confusing print order
4. Identify the error in this Rust code snippet:
fn main() {
    {
        let y = 5;
    }
    println!("{}", y);
}
medium
A. Variable y is used outside its scope
B. Missing semicolon after let y = 5
C. println! macro is misspelled
D. No error, code runs fine

Solution

  1. Step 1: Check where y is declared and used

    Variable y is declared inside inner block and goes out of scope after block ends.
  2. Step 2: Analyze usage of y outside block

    Using y in println! outside block causes error because y is not visible there.
  3. Final Answer:

    Variable y is used outside its scope -> Option A
  4. Quick Check:

    Use inside scope only [OK]
Hint: Variables vanish outside their block scope [OK]
Common Mistakes:
  • Thinking semicolon is missing
  • Assuming println! is wrong
  • Ignoring variable scope rules
5. Consider this Rust code:
fn main() {
    let mut count = 0;
    for i in 0..3 {
        let count = count + i;
        println!("{}", count);
    }
    println!("Final count: {}", count);
}
What will be the output and why?
hard
A. 0\n1\n2\nFinal count: 6
B. 0\n1\n2\nFinal count: 2
C. 0\n1\n2\nFinal count: 0
D. Compilation error due to variable shadowing

Solution

  1. Step 1: Understand variable shadowing inside the loop

    Inside the loop, count is shadowed by a new variable count equal to outer count plus i. Outer count remains unchanged.
  2. Step 2: Trace loop iterations and prints

    Iterations: i=0 -> inner count=0, print 0; i=1 -> inner count=1, print 1; i=2 -> inner count=2, print 2. Outer count stays 0.
  3. Step 3: Final print shows outer count

    After loop, outer count is still 0, so prints "Final count: 0".
  4. Final Answer:

    0 1 2 Final count: 0 -> Option C
  5. Quick Check:

    Shadowing hides outer count, outer unchanged [OK]
Hint: Shadowing inside loop doesn't change outer variable [OK]
Common Mistakes:
  • Assuming outer count changes inside loop
  • Confusing shadowing with mutation
  • Expecting sum accumulation in outer count
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard