fn ninth_fibonacci() {
let mut x = 1;
let mut y = 1;
for number in 1..10 {
let z = x + y;
if number == 9 {
println!("9th Fibonacci number is {} + {} = {}", x, y, z);
println!("");
};
x = y;
y = z;
}
}
in the last 2 lines i had used
let x=y;
let y=z:
instead of
x = y;
y = z;
I didn't get the desired output. I'm not able to understand why i wasn't getting the proper output. I'm basically shadowing right?
thanks for your help !! sorry if I am wrong I just started learning Rust.
Yes, let creates a fresh variable, which is local to the loop body, hence it doesn't update the outer state variables. I.e. let does not mutate or assign, it initializes a completely new and distinct variable.
Note that with let x=y; compiler emits a bunch of warnings about unused variables:
Compiling playground v0.0.1 (/playground)
warning: unused variable: `x`
--> src/lib.rs:10:13
|
10 | let x = y;
| ^ help: if this is intentional, prefix it with an underscore: `_x`
|
= note: `#[warn(unused_variables)]` on by default
warning: unused variable: `y`
--> src/lib.rs:11:13
|
11 | let y = z;
| ^ help: if this is intentional, prefix it with an underscore: `_y`
warning: variable does not need to be mutable
--> src/lib.rs:2:9
|
2 | let mut x = 1;
| ----^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default
warning: variable does not need to be mutable
--> src/lib.rs:3:9
|
3 | let mut y = 1;
| ----^
| |
| help: remove this `mut`
warning: function is never used: `ninth_fibonacci`
--> src/lib.rs:1:4
|
1 | fn ninth_fibonacci() {
| ^^^^^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` on by default
It usually makes sense to pay attention to warning. Also, cc @ekuber, seems like we can give a more precise error when there's "unused mut" and shadowing down the line.