snaggen@programming.dev to Rust@programming.dev · 1 year agoDon't write Rust like it's Javajgayfer.comexternal-linkmessage-square28fedilinkarrow-up169arrow-down16
arrow-up163arrow-down1external-linkDon't write Rust like it's Javajgayfer.comsnaggen@programming.dev to Rust@programming.dev · 1 year agomessage-square28fedilink
minus-squaresleep_deprived@lemmy.worldlinkfedilinkarrow-up3·1 year agoBox is (basically) just the way to have memory on the heap. Here’s a direct comparison of how to do heap memory in C/++ and in rust: int* intOnHeap = (int*)malloc(sizeof(int)); *intOnHeap = 0; MyClass* classOnHeap = new MyClass(); let intOnHeap: Box = Box::new(0); let structOnHeap: Box = Box::new(MyStruct::default()); There can be a bit more to it with custom allocators etc. but that’s the only way most people will use boxes. So Box basically just means “a T is allocated somewhere and we need to free that memory when this value is dropped”.
Box
is (basically) just the way to have memory on the heap. Here’s a direct comparison of how to do heap memory in C/++ and in rust:int* intOnHeap = (int*)malloc(sizeof(int)); *intOnHeap = 0; MyClass* classOnHeap = new MyClass();
let intOnHeap: Box = Box::new(0); let structOnHeap: Box = Box::new(MyStruct::default());
There can be a bit more to it with custom allocators etc. but that’s the only way most people will use boxes. So
Box
basically just means “aT
is allocated somewhere and we need to free that memory when this value is dropped”.