Help me with the concept of Variable shadowing

i write Fibonacci numbers series using the rust Variable shadowing:

fn main() {
    let a = 0;
    let b = 1;
    println!("{}",a);
    println!("{}",b);
    loop
    {
        let c = a + b;
        let a =b;
        let b =c;
        println!("{}",c);
    }
}

but the value of variable c is not getting update and it continuously printing 1
can any one explain me why this happen .

Please put a line of only three backticks

before and after your code, which goes here

so that your code is formatted properly for this forum.
You can click on the edit button under your first post to correct that post as well.

Inside your loop, you're doing let a = … and let b = … instead of a = … and b = …. When you use let, you're creating a new variable, but this new variable only exists for that particular invocation of the loop. If you remove the let in front of a and b in the loop, your program will work correctly.

Before you

remove the let in front of a and b in the loop

also mark a and b as mut, since variables in Rust are immutable by default.

fn main() {
    let mut a = 0;
    let mut b = 1;
    // --snip--
}

i did the Fibonacci numbers using mut , i wand to know the reason why the value of c is not get update.

As @john01dav said before, the let a =b; inside your loop creates a new variable a and shadows (i.e., hides) the previous variable a. These two variables are not connected to each other. The inner variable a is dropped at the end of the scope in which it is introduced, and let c = a + b; always looks up the outer variable a.

In other words, your code is equivalent to:

fn main() {
    let a = 0;
    let b = 1;
    println!("{}", a);
    println!("{}", b);
    loop {
        let c = a + b;
        let d = b;
        let e = c;
        println!("{}", c);
        // d and e are dropped here
    }
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.