Let and let mut

fn main() {
    let length = 10;
    let mut width = 5;
    println!(
        "The oringinal dimensions are length = {} and width = {}",
        length, width
    );
    width = width + 3;
    let length = length * 2;
    println!(
        "The new dimensions are length = {} and width {}.",
        length, width
    );
}

(Playground)

Output:

The oringinal dimensions are length = 10 and width = 5
The new dimensions are length = 20 and width 8.

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 3.65s
     Running `target/debug/playground`

Do you have a question, or did you post to the forum from the Playground by mistake?

The overriding of length is called shadowing.

i am a beginner and i have been using chat gpt to help me solve a few exercises.
What kind of problems is this type of excercise used to solve?

I don't know where you got this exercise from, but your example code appears to showcase the difference between mutating a variable and shadowing one.
See this chapter of The Book:

2 Likes

I would advise against using AI to solve problems for you when you are learning Rust. Or anything else for that matter. However, as you are there, did you ask said AI to explain what that code is demonstrating? I did, it has interesting response.

For me, I like shadowing when I have some data in some type and I convert it into essentially the same data in a different type. For example getting a number input from a user as a String and converting it to integer of float. Using shadowing for the converted value saves me having to dream up a different name for it.

4 Likes

Where can you advise me to start learning rust
And the necessary tools, now that I know where I can ask questions when stuck

https://doc.rust-lang.org/stable/book/ and GitHub - rust-lang/rustlings: 🦀 Small exercises to get you used to reading and writing Rust code!.

Both are linked from Learn Rust - Rust Programming Language.