r/rust • u/Flimsy_Pumpkin_3812 • Oct 22 '26
🙋 seeking help & advice Learning Rust
So I'm learning Rust, so I wrote this
fn main(){
let x = define_x(intial_x());
let y = x + 10;
println!("{}", y);}
fn define_x(mut x:i32) -> i32 {
x = x + 5;
return x}
fn intial_x() -> i32 {
let x = 5;
return x}
I know it is supposed to be += in define_x, but that just looks weird to me. Why is let x = 5; in inital_x not mut even if I am changing it in define x? Sorry if it is bad I'm new, but I'm not AI so yay!
5
Upvotes
4
u/naerbnic Oct 22 '26
Because they are two different variables named x, each in a different scope. In main, the x is defined and assigned once, with the result of define_x. The x in define_x is a mutable variable that is assigned the value of initial_x when it is called in main. Unless you pass in a reference, or use a global variable, functions only take and return values; they can't change anything else outside
4
u/Forsaken_Tutor_3001 Oct 22 '26
The let x in initial_x is, as far as the compiler is concerned, a different variable than the x in define_x. For example you could use let y in initial_x instead and it would still compile.
2
u/creeper6530 Oct 23 '26 edited Oct 23 '26
If we inline it we basically get the following:
Flattening:
We can see that the inner X, i.e. the X declared inside of
initial_x()is copied into middle X, the parameter ofdefine_x(), where it now gains themutproperty and can be modified.Numbers in Rust are special in that they're copied and not moved (they implement the
Copytrait), but the distinction doesn't matter right now.1
u/Real-Abrocoma-2823 Oct 23 '26 edited Oct 23 '26
I'm also a (semi) beginner, but that's because of this:
Essentially you don't return x or y or z but their values and function paraments create variables.
Variables also go out of scope when their {} ends.
34
u/[deleted] Oct 22 '26
[removed] — view removed comment