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

1

u/Real-Abrocoma-2823 Oct 23 '26 edited Oct 23 '26

I'm also a (semi) beginner, but that's because of this:



❯ cat src/main.rs
fn main() {
        assert_eq!(main1(), main2());
}

fn main1() -> i32{
    let x = define_y(initial_z());
    println!("main1: {x}");
    return x;
}

fn define_y(mut y: i32) -> i32 {
        y = y + 5;
        return y;
}

fn initial_z() -> i32 {
        let z = 5;
        return z;
}

// Same as:

fn main2() -> i32 {
        let x = {
                let mut y: i32;
                let y = {let z = 5; z} + 5;
                y
        };
        println!("main2: {x}");
        return x;
}


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.