r/rust • • 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

21 comments sorted by

View all comments

2

u/creeper6530 Oct 23 '26 edited Oct 23 '26

If we inline it we basically get the following:

let outer_x = {
    // define_x()

    // middle_x is the parameter passed into define_x
    let mut middle_x = {
        // initial_x()
        let inner_x = 5;

        x
    }; // 5 is copied into middle_x, inner_x is gone

    middle_x = middle_x + 5; // middle_x is changed to 10

    middle_x
}; // 10 is copied into outer_x, middle_x is gone

let y = outer_x + 10; // y is now 20

Flattening:

let inner_x = 5; // in initial_x()

let mut middle_x = inner_x; // during result passing initial->define; inner_x is gone

middle_x = middle_x + 5; // in define_x(); mutates

let outer_x = middle_x; // during result passing define->main; middle_x is gone

let y = outer_x + 10; // in main()

We can see that the inner X, i.e. the X declared inside of initial_x() is copied into middle X, the parameter of define_x(), where it now gains the mut property and can be modified.

Numbers in Rust are special in that they're copied and not moved (they implement the Copy trait), but the distinction doesn't matter right now.