Help needed with variable mutability

Hi, I have started learning Rust and am following the tutorial book.

right now I am trying to generate the nth Fibonacci number (using loop based approach), The problem is my variables in the loop do not get updated as I expect them to, in the first iteration i can see that the second_last_number is updated but then all variable remain the same in all iterations

use std::io;

fn main() {

println!("Enter number : ");
let mut number = String::new();


io::stdin().read_line(&mut number)
    .expect("Failed to read line");

let number: u32 = number.trim().parse()
    .expect("Please type a number!");

let last_number: i32 = 1;
let second_last_number: i32 = 0;
let result: i32 = 0;

for x in 1..number + 1{
    println!("index : {}", x);
    let result = last_number + second_last_number;
    println!("result : {}", result);
    let second_last_number = last_number;
    println!("second : {}", second_last_number);
    let last_number = result;
    println!("last : {}", last_number);
}

println!("{} fibonnaci number is {}", number, result);

}

let declares a new variable, even if a variable of the same name already exists. And variables only live as long as their scope. So in the loop when you do let last_number you've created a new last_number variable that only lives until the end of that iteration of the loop. Once it loops around, that last_number no longer exists and you're back to using the last_number you declared before the loop started (which is always 1).

So if don't use let here then = will assign to a variable that already exists instead of creating a new one:

for x in 1..number + 1{
    println!("index : {}", x);
    result = last_number + second_last_number;
    println!("result : {}", result);
    second_last_number = last_number;
    println!("second : {}", second_last_number);
    last_number = result;
    println!("last : {}", last_number);
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.