Hacker News new | past | comments | ask | show | jobs | submit login

Does rust really allow stack allocated objects to escape function lifetime? That seems antithetical to how a stack works.



It's the other way around; Rust is really good at tracking the lifetime of objects, and so Rust code is a lot more reckless with passing around pointers to stack-allocated objects through very long chains of functions, iterators, closures, etc, because it becomes obvious when a mistake was made (it becomes a compile error).

This makes it so that things that appear dangerous in C++ are safe in Rust, so for example instead of defensively allocating std::string to store strings (because who knows what might happen with the original string), Rust can just keep using the equivalent of std::string_view until it becomes obvious that it's no longer possible.


This (avoiding needless copies due to uncertainty of what the callee might do, e.g. caching a reference) makes sense but is not what the grandparent was suggesting.


It's exactly what I was talking about. Rust enables me to avoid using the heap when I would be forced to in C/C++. And thanks to the borrow checker ensuring safety in doing so, this extends to libraries and dependent code in ways not easily achievable in C/C++. The net effect is a profound reduction in heap usage by comparison.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: