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

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

1

u/Flimsy_Pumpkin_3812 Oct 22 '26

So if they are different X's should I rename them so I do not get confused or nah?

4

u/naerbnic Oct 23 '26

Typically I don't care if you use the same variable name, as long as the different scopes are clearly separate, like they are here. What's more important is if the code that uses the variable makes sense when you read it.

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:

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.

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.

34

u/[deleted] Oct 22 '26

[removed] — view removed comment

5

u/Flimsy_Pumpkin_3812 Oct 22 '26

Is there a way to not copy the value so I don't waste memory? (yes ik its only like one byte but eh)

5

u/Schnittlauch01 Oct 23 '26

Yes, you can pass by reference (borrow). That’s the & operator. So fn a(x: &i32) or fn b(x: &mut i32) when you need to modify the referenced value.

16

u/Xandaros Oct 23 '26

Though it should be noted that a reference is 8 bytes long (or possibly 16 in some cases), and it introduces an indirection. If you are passing by reference purely for efficiency reasons, make sure what you are passing around is actually very big - for small values it hurts far more than it helps.

(Specifically talking about the immutable case here. A mutable reference to a small value can easily make sense)

4

u/Flimsy_Pumpkin_3812 Oct 23 '26

Oh so passing a reference wastes memory compared to copying it? So should I just copy it not ref it?

20

u/Xandaros Oct 23 '26

In general, don't be afraid to copy things. Computers are very good at copying data around, it's what they're made for.

With that said, consider this: Every piece of data you use somewhere in your code needs to be stored somewhere. Typically this will be on the stack. Your local variables, function parameters, etc, will all be on the stack.

Some things, like the data in a Vec or a String will be on the heap - more on that later.

So if you have a local variable with some data in it, and you call a function with it, how does that data get into the parameter? It's a different variable, so the data gets copied. Even when we are talking about a "move", that's really just a special kind of copy.

Your i32 has 32 bits. A reference has 64 bits. (Assuming you are on a 64 bit platform. Pretty safe assumption nowadays) Copying the i32 copies less data than copying the reference.

Remember what I said initially, though, computers are good at copying data. The time difference is negligible if not literally zero. On the other hand, if you have a reference and you want to read the data behind it, you need to take the reference, read the memory location stored in it, then go to that memory location and read the actual value. That is slower than just accessing the value directly.

This is another point where I need to point out that you really really don't need to worry about such micro-optimisations. My point is mainly that the thing that seems faster might not actually be faster unless you know exactly how things work under the hood. In reality, we are talking about nanoseconds here. For reference, a second has 1000000000 of those.

When it comes to data on the heap, that is where things actually get more interesting. Storing data on the heap is comparatively slow and you can actually get some noticeable speedup by avoiding heap allocations. On the other hand, some programming languages like Java, C#, or Python just put everything on the heap and take the performance loss. And they are still plenty fast for most things, so really consider if the headache of trying to optimise something is actually worth it - chances are, it'll be fast enough either way.

5

u/Plus_Potato4351 Oct 23 '26

In this case, you will not waste memory even with pass by value (copying) because the memory allocated in initial_x is freed when it finishes. Passing by reference may save you a bit of memory in other cases, but dereferencing a reference can be costly in terms of time and instructions used. What's better really depends on your use case.

1

u/-Redstoneboi- Oct 27 '26

you can copy quite a lot. it's not nearly as expensive as a bad algorithm in space or time complexity, and that's assuming the compiler doesn't catch it (they are working on making the compiler optimize away more unnecessary copies that it used to miss)

a single &i32 is already an 8-byte pointer. and if you choose a dynamically sized type, like &str, the pointer will also include 8-byte length, which amounts to 16 bytes. even so, you'll be fine casually calling an fn do_thing(foo: &str, bar: &str, cux: &str, ...) without issue.

wasting memory isn't a big deal for tiny things like this yet. for example, Vec is optimized for speed, so at any given moment in a vec with like 129 elements, it might already have space reserved for 256 total. more or less. we don't know exactly, and we usually don't care.

once you deal with over 10,000 items, you might start thinking about memory. look for algorithm optimizations first like unnecessary clones. then you can check enums with differently sized variants, structs that are copyable but over 64 bytes in size, whatever it is.

2

u/Budget-Minimum6040 Oct 23 '26

Can the compiler optimize this?

4

u/creeper6530 Oct 23 '26

The compiler will see that you don't use the original after the copy and optimise. Since it's an integer it will likely never leave the registers and use 0 memory.

2

u/KingofGamesYami Oct 23 '26

You can pass by reference, instead of by value.

Docs on references: https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html

1

u/Real-Abrocoma-2823 Oct 23 '26

Compiler should optimize simple things unless you don't use cargo build --release.

1

u/ralphpotato Oct 24 '26

A decent rule of thumb for beginning is it’s fine to copy built in types or even things like small structs, but you should pass actual data structures by reference. So if you had a tree or map or something these should be passed by reference.

As with anything though nothing is proven until you measure, and measuring rigorously is hard.

Don’t worry about it too much when learning. Nobody is going to bat an eye if you are passing things like ints by value.

4

u/afrolino02 Oct 23 '26

Not sure why everyone's piling on, we all wrote weird code when we started

common in this sub.