A question about variables and constants

Hello,
In the Rust-Lang a variable is like a constant in other programming language and its value cannot be changed unless the word 'mut' is used. Why does code 1 allow changing the value of 'number1', but code 2 shows an error?

Code 1:

fn main() {    
           let number1;
           let number2 = 22;
           number1 = number2;
           print!("{}", number1);
        }

Code 2:

fn main() {    
           let mut number1;
           let mut number2 = 22;
           number1 = number2;
           print!("{}", number1);
        }

Please answer my question briefly.

Thank you.

For code1, let number1; declares an uninitialized variable. Rust allows immutable variables to be declared uninitialized and then initialized once later. This is not strictly speaking a mutation. If you try to mutate number1 again after the first initialization it will be an error.

For code2, there is no error but you are probably seeing warnings about unnecessary mut modifiers. As explained above, because number1 was declared uninitialized, the assignment is actually initialization not mutation, so number1 is never actually mutated, which is why the compiler thinks the mut declaration is not needed.

2 Likes

Side note: let x = y; doesn't mean that x is constant. For example, if that line is part of a loop, then x will hold different values for each time the loop repeats.

I acknowledge that in some languages it still is referred to as "constant". Just note that constants (const) in Rust are "really" constant at compile time.

2 Likes

Hello,
Thank you so much for all replies.
I have another question. As @jbe said, the number1 is not a constant really, but why its value can only be changed once.
For example, why code 1 shows me an error, but code 2 doesn't:

Code 1:

fn main() {    
           let number1;
           let number2 = 22;
           number1 = number2;
           print!("{}", number1);
           number1 = 23;
           print!("{}", number1);
        }

Code 2:

fn main() {    
           let mut number1;
           let number2 = 22;
           number1 = number2;
           print!("{}", number1);
           number1 = 23;
           print!("{}", number1);
        }

Thanks.

Did you read the previous answers? Assigning the first value of an uninitialized variable is not "changing", it's initilaization. That's allowed for any variable.

The second assignment would be mutation, which is obviously not allowed for immutable bindings, this is completely logical.

You are basically asking "why can't a non-mut variable be mutated while a mut one can?", and the answer is "because that's the whole point of mut."

1 Like

Hello,
Thank you so much for your reply.
So, initilaization vs. change.

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.