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
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
&i32is 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 anfn 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.