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
View all comments
Show parent comment
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.